6

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?

ankhuri
  • 179
  • 11
Phalguni Mukherjee
  • 623
  • 3
  • 11
  • 29

2 Answers2

13

try SecureRandom API.

SecureRandom random = new SecureRandom();
byte bytes[] = new byte[16]; // 128 bits are converted to 16 bytes;
random.nextBytes(bytes);
Pramod S. Nikam
  • 4,271
  • 4
  • 38
  • 62
7

UUID

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

Community
  • 1
  • 1
Bilbo Baggins
  • 2,899
  • 10
  • 52
  • 77
  • `java.util.UUID/randomUUID` is not suitable for general purpose 128 bit random number generation, since it only generates 122 random bits. See https://en.wikipedia.org/wiki/Universally_unique_identifier#Version_4_.28random.29 – David J. Sep 29 '14 at 15:10
  • 1
    @DavidJames Please explain more as it is mentioned in the javadocs for UUID "A class that represents an immutable universally unique identifier (UUID). A UUID represents a 128-bit value." I understand that it actually generates 122 bits only. but its also unique across the world isn't it? – Bilbo Baggins Mar 17 '15 at 15:30
  • 1
    Both comments are correct: In a random-based UUID only, 122 of the 128 bits is randomly generated. So technically not meeting the 128-bits of randomness asked in the Question. But practically speaking, in real-world work, both have have about the same chance of collisions: virtually nil. For critical security applications, the random UUID may not be appropriate, but for other non-critical applications the random UUID works well and is handy with just a short line of code using built-in Java class. – Basil Bourque Feb 06 '17 at 15:52