I want to generate a 128 bit random key in java. I am using the following:
byte[] byteBucket = new byte[bytelength];
randomizer.nextBytes(byteBucket);
Will my byte array length be 16 as (16*8=128) or 128?
I want to generate a 128 bit random key in java. I am using the following:
byte[] byteBucket = new byte[bytelength];
randomizer.nextBytes(byteBucket);
Will my byte array length be 16 as (16*8=128) or 128?
try SecureRandom API.
SecureRandom random = new SecureRandom();
byte bytes[] = new byte[16]; // 128 bits are converted to 16 bytes;
random.nextBytes(bytes);
There is a class called java.util.UUID
, with a method to generate a random-based UUID. This 128-bit value has 122 of its bits generated randomly.
UUID uuid = UUID.randomUUID() ;
Call toString
to view the value as a hex string in canonical format with hyphens inserted.
uuid.toString(): 24b47cf5-fb53-4fb1-a5a2-8b415260304d
You can extract the 128 bits as a pair of 64-bit long
integer numbers. Call getMostSignificantBits()
and getLeastSignificantBits()
.
long mostSignificant = uuid.getMostSignificantBits() ;
long leastSignificant = uuid.getLeastSignificantBits() ;
This value may not be appropriate for critical security applications with 4 bits being predictable (not random). But in other practical applications, this handy class may work well.
Here is a question which I found on SO with more detailed explanation: Likelihood of collision using most significant bits of a UUID in Java