How to properly use SecureRandom 12 digit number?

169 Views Asked by At

I am trying to create a random number use SecureRandom. It must be digits only (0123456789) and be 12 characters long. Any help would be greatly appreciated.

    SecureRandom secureRandom = new SecureRandom();
    synchronized (secureRandom) {
        final byte[] random = new byte[12];
        secureRandom.nextBytes(random);
        return Base64.encodeBase64URLSafeString(random);
    }

I am getting the following:

IHmv_qsWMZ0teI_-
1

There are 1 best solutions below

0
WJS On

I am trying to create a random number using SecureRandom. It must be digits only (0123456789) and be 12 characters long.

You could doit like this. Just specify the origin and bound to match your digit count requirements.

SecureRandom secureRandom = new SecureRandom();
long random =  secureRandom.nextLong(100_000_000_000L,1_000_000_000_000L);
System.out.println(random);

prints something like

426491911225

If it must be in a byte array of individual digits, you can do the following:

byte[] bytes = new byte[12];
int loc = bytes.length - 1; // insert in reverse in array

while(random > 0) {
    bytes[loc--] = (byte)(random%10);
    random/=10;
}
System.out.println(Arrays.toString(bytes));

prints

[4, 2, 6, 4, 9, 1, 9, 1, 1, 2, 2, 5]