Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AES random key generation

I see many examples where the secret key is generated this way:

KeyGenerator generator = KeyGenerator.getInstance("AES");
generator.init(KEY_LEN);
SecretKey secretKey = generator.generateKey();

I'm in doubt if there's a difference (even conceptual) with the following:

byte[] material = new byte[KEY_LEN / Byte.SIZE];
SecureRandom.getInstanceStrong().nextBytes(material);
SecretKey secretKey = new SecretKeySpec(material, "AES");

Stated that both methods are 3 lines, is there some practical impact in preferring the first over the second?

Thanks

like image 652
Michele Mariotti Avatar asked Sep 22 '26 17:09

Michele Mariotti


1 Answers

You could look at the actual source code for generateKey() to see the difference but ultimately they are both going to do the same steps to generate an AES key. I would argue the latter

byte[] material = new byte[KEY_LEN / Byte.SIZE];
SecureRandom.getInstanceStrong().nextBytes(material);
SecretKey secretKey = new SecretKeySpec(material, "AES");

is a little more brittle for the average coder, requiring them to understand the SecureRandom class. If you eliminate the second line altogether the code runs just fine with an all zero key, an obvious vulnerability that's also easy for an attacker to check. Also, using generateKey() can produce a properly formatted key if the algorithm has some particular requirements. For example, the now obsolete DES and Triple DES algorithms had a weird parity bit in each byte that some DES implementations expected to see.

like image 86
President James K. Polk Avatar answered Sep 25 '26 08:09

President James K. Polk