Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate a symmetric key with Bouncy Castle?

How can I generate a symmetric key with Bouncy Castle? Both PrivateKeyFactory and PublicKeyFactory seem related to AsymmetricKeyParameter.

I don't want to know any JCA/JCE API - instead I'm only interested in Bouncy Castle specific API.

Can (should) I just generate a random bytes?

like image 581
Jin Kwon Avatar asked Jul 23 '13 01:07

Jin Kwon


1 Answers

AES does not have any weak keys, so a straightforward random generation should be fine.

// SecureRandom is expensive to initialize (takes several milliseconds) –
// consider keeping the instance around if you are generating many keys.
SecureRandom random = new SecureRandom();
byte[] keyBytes = new byte[16];
random.nextBytes(keyBytes);
SecretKeySpec key = new SecretKeySpec(keyBytes, "AES");
like image 71
ntoskrnl Avatar answered Sep 23 '22 05:09

ntoskrnl