views:

157

answers:

4

I got the following method body to generate a key for encryption:

new BigInteger(500, new SecureRandom()).toString(64);

Could anyone explain what is the size of generated key?

A: 

It's a secure random number with a length of 500 bit in your case. Have a look at the javadoc of the BigInteger(int numBits, Random rnd) constructor.

Andreas_D
Assuming that I want key size 128 should it be:new BigInteger(128, new SecureRandom()).toString(32) ?What is the reason for adding toString method?
Kumar
First: yes. The toString() method converts the number into a String. I'd choose 'toString(16)' for hexadecimal or just 'toString()' for decimal numbers in the String
Andreas_D
A: 

Your line of code creates a 500 bit integer and apparently tries to convert it to a String in Base64 - that's the toString() call. But that won't work, because BigInteger.toString() only works up to base 36 and defaults to decimal otherwise. If you need a Base64 representation, you have to use a third-party class, as there is AFAIK no Base64 encoder in the standard API.

Michael Borgwardt
Thanks for the reply. What about this one:new BigInteger(128, new SecureRandom()).toString(32) <- Does it mean that it generate valid key with 128 bit?
Kumar
Yes, though it will represent it in base 32 - which is probably not what you want. It depends on the API you want to use the key for, in what format it expects the key.
Michael Borgwardt
A: 

Normally you would want your encryption key to be a power of 2. So perhaps you mean 512 bits?

Darioush
There was a mistake, so for instance:new BigInteger(256, new SecureRandom()).toString(32) - what is the purpose for adding "toString(32)" in that case?
Kumar
A: 

First, as other suggested, you will get IllegalArgumentException because BigInteger doesn't support radix 64.

Even if you use a valid radix, the number of characters generated varies because BigInteger strips leading 0s and you might also get minus sign in the string.

To get random keys, just use random bytes directly. Say you want 128-bit (16 bytes) AES key, just do this,

  byte[] keyBytes = new byte[16];
  new SecureRandom().nextBytes(keyBytes);
  SecretKey aesKey = new SecretKeySpec(keyBytes, "AES");
ZZ Coder