Search code examples
javacryptographykeyaesbouncycastle

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?


Solution

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