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?
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?
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.
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.
Normally you would want your encryption key to be a power of 2. So perhaps you mean 512 bits?
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");