I'm a little bit confused, how to do this. I know I can use Random class to generate random numbers, but I don't know how to specify and generate 8-byte number?
Thanks, Vuk
The java. util. Random. nextBytes() method generates random bytes and provides it to the user defined byte array.
To create a single random byte, it calls the Math. random() * 256 function. This creates a random floating point number in the range from 0 to 255.
To generate Random Hexadecimal Bytes, first, a random byte can be generated in decimal form using Java. util. Random. nextInt() and then it can be converted to hexadecimal form using Integer.
urandom() method is used to generate a string of size random bytes suitable for cryptographic use or we can say this method generates a string containing random characters. Return Value: This method returns a string which represents random bytes suitable for cryptographic use.
You should note that the java.util.Random
class uses a 48-bit seed, so not all 8-byte values (sequences of 64 bits) can be generated using this class. Due to this restriction I suggest you use SecureRandom
and the nextBytes
method in this situation.
The usage is quite similar to the java.util.Random
solution.
SecureRandom sr = new SecureRandom();
byte[] rndBytes = new byte[8];
sr.nextBytes(rndBytes);
Here is the reason why a 48-bit seed is not enough:
Random
class implements a pseudo random generator which means that it is deterministic.Random
determines the future sequence of bits.Random
object.Based on @Peter Lawreys excellent answer (it deserves more upvotes!): Here is a solution for creating a java.util.Random
with 2×48-bit seed. That is, a java.util.Random
instance capable of generating all possible long
s.
class Random96 extends Random {
int count = 0;
ExposedRandom extra48bits;
class ExposedRandom extends Random {
public int next(int bits) { // Expose the next-method.
return super.next(bits);
}
}
@Override
protected int next(int bits) {
if (count++ == 0)
extra48bits = new ExposedRandom();
return super.next(bits) ^ extra48bits.next(bits) << 1;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With