How to generate a symmetric key with Bouncy Castle

2019-05-10 23:12发布

问题:

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?

回答1:

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");