I am trying to encrypt some content using ECC algorithm using BouncyCastle in java. But I am getting exception of BouncyCastle library saying cannot cast JCEECPublicKey
to IESKey
. Which I understood that the public key generated by KeyPairGenerator
is JCEECPublicKey
which cannot be used in java Cipher.init
method. Can someone tell me how can convert it in Public key or X509 spec so that I can use it in encryption.
Here is the code which I tried
// add instance of provider class
Security.addProvider(new BouncyCastleProvider());
// initializing parameter specs secp256r1/prime192v1
ECParameterSpec ecSpec = ECNamedCurveTable.getParameterSpec("prime192v1");
// key pair generator to generate public and private key
KeyPairGenerator generator = KeyPairGenerator.getInstance("ECDH", new BouncyCastleProvider());
// initialize key pair generator
generator.initialize(ecSpec);
// Key pair to store public and private key
KeyPair keyPair = generator.generateKeyPair();
Cipher iesCipher = Cipher.getInstance("ECIES", new BouncyCastleProvider());
iesCipher.init(Cipher.ENCRYPT_MODE, keyPair.getPublic());
Also I tried to convert the public key into X509EncodedSpec but I get same exception
X509EncodedKeySpec spec = new X509EncodedKeySpec(keyPair.getPublic().getEncoded());
KeyFactory factory = KeyFactory.getInstance("ECDH");
PublicKey publicKey = factory.generatePublic(spec);
The exception which I am getting is
java.lang.ClassCastException: org.bouncycastle.jce.provider.JCEECPublicKey cannot be cast to org.bouncycastle.jce.interfaces.IESKey
at org.bouncycastle.jce.provider.JCEIESCipher.engineGetKeySize(JCEIESCipher.java:49)
at javax.crypto.Cipher.passCryptoPermCheck(Cipher.java:1057)
at javax.crypto.Cipher.checkCryptoPerm(Cipher.java:1015)
at javax.crypto.Cipher.init(Cipher.java:1229)
at javax.crypto.Cipher.init(Cipher.java:1173)
at com.test.EciesTest.main(EciesTest.java:45)
EDIT
Based on comment the JDK version I am using is JDK 7 - Oracle Import statements I am using:
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.Security;
import java.security.spec.ECGenParameterSpec;
import javax.crypto.Cipher;
import org.bouncycastle.jce.provider.BouncyCastleProvider;