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 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")?
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.