import java.security.SecureRandom
/** Production-grade utility object for generating cryptographically secure 8-digit numbers and string codes.
*/
object RandomCodeGenerator {
// Thread-safe instance of SecureRandom backed by OS entropy
private val secureRandom: SecureRandom = new SecureRandom()
// Numerical constants with underscore separators for readability
private val Min8DigitInt: Int = 10_000_000
private val RangeSize: Int = 90_000_000 // Generates offset in [0, 89_999_999]
private val CodeUpperExclusive: Int = 100_000_000 // Generates raw value in [0, 99_999_999]
/** 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.
*/
def generate8DigitNumber(): Int = {
// nextInt(n) returns a uniform pseudo-random value between 0 (inclusive) and n (exclusive)
Min8DigitInt + secureRandom.nextInt(RangeSize)
}
/** Generates an 8-character numeric string code between "00000000" and "99999999". Preserves leading zeros using format specifiers, making it suitable for OTPs, PINs, or verification tokens.
*
* @return
* An 8-character numeric string with leading zero padding if needed.
*/
def generate8DigitCode(): String = {
val rawValue: Int = secureRandom.nextInt(CodeUpperExclusive)
// Modern Scala String Interpolator (f-interpolator) using standard printf syntax
// %08d guarantees a min width of 8 digits, padded with leading zeros
f"$rawValue%08d"
}
}
// ==========================================
// Example Execution & Usage
// ==========================================
object Application {
def main(args: Array[String]): Unit = {
println("=== Generating 8-Digit Integers [10000000 - 99999999] ===")
for (_ <- 1 to 3) {
val randomNumber: Int = RandomCodeGenerator.generate8DigitNumber()
println(s"Generated integer: $randomNumber")
}
println("\n=== Generating 8-Digit OTP Codes [00000000 - 99999999] ===")
for (_ <- 1 to 3) {
val randomCode: String = RandomCodeGenerator.generate8DigitCode()
println(s"Generated OTP code: $randomCode")
}
}
}
/*
run:
=== Generating 8-Digit Integers [10000000 - 99999999] ===
Generated integer: 41449558
Generated integer: 14259159
Generated integer: 23364998
=== Generating 8-Digit OTP Codes [00000000 - 99999999] ===
Generated OTP code: 17885887
Generated OTP code: 03028232
Generated OTP code: 79164688
*/