Java RSA encryption with public key

I'm trying to encrypt a file with a public key I get from a certificate.

PublicKey publicKey = cert.getPublicKey();
cipher = Cipher.getInstance("RSA", "BC");        
cipher.init(Cipher.ENCRYPT_MODE, publicKey);

throws an exception: java.lang.IllegalArgumentException: not an RSA key!

I've tried :

KeyFactory keyFactory = KeyFactory.getInstance("RSA");
X509EncodedKeySpec spec = new X509EncodedKeySpec(publicKey.getEncoded());
PublicKey rsaPublicKey = KeyFactory.getInstance("RSA").generatePublic(spec);

but that throws Invalid RSA public key

The constractor of org.bouncycastle.asn1.pkcs.RSAPublicKey expects 2 BigIntegers (probably the modulus and the public exponent).

Looking into cert.getPublicKey() reveals its a DSAPublicKeyImpl.

How can I convert it into an RSAPublicKey (or anything else) usable by Cipher.getInstance("RSA", "BC")?


DSA keys can't be used for RSA encryption. DSA is only for signatures, and it uses different math requiring different key information.

Generate an RSA key instead, and use it with a library implementing a standard like CMS or PGP (BouncyCastle supports both). These use a random key for a symmetric cipher to encrypt the file, then encrypt that key with the public key of each recipient. There are many reasons this is a better approach.

Need Your Help

Concat two column in a select statement sql server 2005

sql-server-2005 select concat

How to Concat two column in a select statement sql server 2005?

Spring and Soap API error: "Unable to validate using XSD: Your JAXP provider"

java spring soap paypal

I had a Spring based java app that connected to PayPal using their Soap API. It was working fine with Jetty, but when I tried to deploy it with Tomcat, I got the following error: