xkcd
xkcd

Reputation: 472

RSA key generation error using BouncyCastle API

I have a very simple and short program:-

Security.addProvider(new BouncyCastleProvider());
RSAKeyPairGenerator kpg = new RSAKeyPairGenerator();
kpg.init(new KeyGenerationParameters(new SecureRandom(), 2048));
kpg.generateKeyPair();

According to the BoucnyCastle API, I should get an RSA key pair as a result of this. Instead I am getting:-

Exception in thread "main" java.lang.ClassCastException: org.bouncycastle.crypto.KeyGenerationParameters cannot be cast to org.bouncycastle.crypto.params.RSAKeyGenerationParameters
at org.bouncycastle.crypto.generators.RSAKeyPairGenerator.init(Unknown Source)

Any ideas why? Thanks.

Upvotes: 1

Views: 990

Answers (1)

Lothar
Lothar

Reputation: 5449

You're using the provider specific generator, so you must use the provider specific parameter classes as well. Alternatively use the JCE API in a provider independent manner:

KeyPairGenerator gen = KeyPairGenerator.getInstance("RSA", "BC");
gen.initialize(2048, new SecureRandom());
KeyPair kp = gen.generateKeyPair();

This still uses BouncyCastle but all provider specific stuff is hidden behind the JCE API.

Upvotes: 2

Related Questions