Search code examples
javacryptographyrsabouncycastle

Effective Implementation of RSA Public Key Generation and Encryption in Java


I am currently trying to write a program that will utilize a public key cryptosystem such as RSA or ElGamal. I have been looking at different sources, and the closest I have gotten was in the Bouncy Castle FIPS documentation of public key encryption, where the sample code for RSA is somewhat simple:

public byte[] pkcs1Encrypt(RSAPublicKey pubKey, byte[] data) {    
   Cipher c = Cipher.getInstance(“RSA/NONE/PKCS1Padding”, “BCFIPS”);
   c.init(Cipher.ENCRYPT_MODE, pubKey);
   return c.doFinal(data);
} 

I've worked often with symmetric key cryptosystems such as AES and Triple-DES (DESede), but I looked under the Bouncy Castle documentation, and found out that the RSAPublicKey is not a sub-interface/class of the SecretKey class.

Is there any way to generate this RSAPublicKey object, or is there a more efficient way to implement this kind of encryption with Bouncy Castle or the JCE


Solution

  • The bouncycastle document is not clear. cipher.init(Cipher.ENCRYPT_MODE, pubKey); requires an instance of java.security.interfaces.RSAPublicKey and not org.bouncycastle.asn1.pkcs.RSAPublicKey

    You can build RSAPublicKey using modulus and exponent, from the DER encoded data, or you can generate a new key pair

    //RSA public key from DER encoded data
    byte publicKeyData[] = ...;
    X509EncodedKeySpec keySpec = new X509EncodedKeySpec(publicKeyData);
    KeyFactory kf = KeyFactory.getInstance("RSA");
    PublicKey publicKey = kf.generatePublic(keySpec );
    
    //RSA from modulus and exponent
    RSAPublicKeySpec keySpec = new RSAPublicKeySpec(modulus, publicExponent);
    KeyFactory kf = KeyFactory.getInstance("RSA");
    PublicKey publicKey = kf.generatePublic(keySpec);
    
    //Generate a key pair using a secure random algorithm
    KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
    SecureRandom random = SecureRandom.getInstance("SHA1PRNG", "SUN");
    keyGen.initialize(2048, random);
    KeyPair pair = keyGen.generateKeyPair();
    PrivateKey privateKey = pair.getPrivate();
    PublicKey publicKey = pair.getPublic();
    byte publicKeyData[] = publicKey.getEncoded();