How to generate an 8 digits random number in Kotlin

1 Answer

0 votes
package com.example.random

import java.security.SecureRandom

// Thread-safe instance of SecureRandom backed by OS entropy
private val secureRandom = SecureRandom()

// Constant definitions with underscore separators for readability
private const val MIN_8_DIGIT_INT = 10_000_000
private const val MAX_8_DIGIT_INT = 99_999_999
private const val CODE_UPPER_EXCLUSIVE = 100_000_000

/**
 * Generates a cryptographically secure 8-digit integer between 10,000,000 and 99,999,999 (inclusive).
 * Guaranteed to start with a non-zero digit (1-9).
 *
 * @return An 8-digit positive integer.
 */
fun generate8DigitNumber(): Int {
    // Kotlin's IntRange (min..max) handles inclusive bounds cleanly.
    // SecureRandom.nextInt(min, maxExclusive) is available in Java 17+/Kotlin JVM.
    // For universal compatibility across all JVM versions, we use range arithmetic:
    val rangeSize = (MAX_8_DIGIT_INT - MIN_8_DIGIT_INT) + 1 // 90,000,000
    return MIN_8_DIGIT_INT + secureRandom.nextInt(rangeSize)
}

/**
 * Generates an 8-character numeric string code between "00000000" and "99999999".
 * Preserves leading zeros using String.format, making it suitable for OTPs, PINs, or tokens.
 *
 * @return An 8-character numeric string padded with leading zeros if necessary.
 */
fun generate8DigitCode(): String {
    // Generates a raw value in the range [0, 99_999_999]
    val rawValue = secureRandom.nextInt(CODE_UPPER_EXCLUSIVE)

    // String formatting with %08d guarantees a minimum width of 8 digits with leading zero padding
    return String.format("%08d", rawValue)
}

// ==========================================
// Example Execution
// ==========================================

fun main() {
    println("=== Generating 8-Digit Integers [10000000 - 99999999] ===")
    repeat(3) { index ->
        val randomNumber = generate8DigitNumber()
        println("Generated integer #${index + 1}: $randomNumber")
    }

    println("\n=== Generating 8-Digit String Codes [00000000 - 99999999] ===")
    repeat(3) { index ->
        val randomCode = generate8DigitCode()
        println("Generated OTP code #${index + 1}: $randomCode")
    }
}


/*
run:

=== Generating 8-Digit Integers [10000000 - 99999999] ===
Generated integer #1: 55374651
Generated integer #2: 60501712
Generated integer #3: 42917903

=== Generating 8-Digit String Codes [00000000 - 99999999] ===
Generated OTP code #1: 13815866
Generated OTP code #2: 28291987
Generated OTP code #3: 12289359

*/

 



answered Oct 3 by avibootz
...