1

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 java.security.spec.InvalidKeySpecException: java.security.InvalidKeyException: 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")?

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Yes, I am actually trying to encrypt a symmetric key, I was just trying to simplify the problem. Still, I cant generate the recipient's keys, I have his certificate, how can I encrypt the key for him?
@user3116865 DSA is for signatures only. If the recipient wants to receive encrypted messages, he'll need to conduct Diffie-Hellman key exchange, signing his contribution to the exchange with his DSA certificate, or generate a new RSA key pair so that you can encrypt the key.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.