George
George

Reputation: 27

Encrypt data with RSA public key in Java and decrypt in Crypto++

I'm trying to encrypt data with RSA public key in Java and decrypt it in Crypto++. It results in an error:

"RSA/EME-PKCS1-v1_5: ciphertext length of 24 doesn't match the required length of 128 for this key"

What am I doing wrong?

Java:

String cipher = Encryption.encryptStrRSA(txt, pubKeyk);

public static String encryptStrRSA(String str, PublicKey pubKey)
    throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException,
    IllegalBlockSizeException, BadPaddingException, NoSuchProviderException {

    Cipher cipher = Cipher.getInstance("RSA/NONE/PKCS1Padding", "BC");
    cipher.init(Cipher.ENCRYPT_MODE, pubKey);

    byte[] encryptedAesKey = cipher.doFinal(str.getBytes());
    String cipherStr = new String(encryptedAesKey);

    System.out.println(cipherStr);
    return cipherStr;
}

public static PublicKey strToPublicKey(String key64) throws GeneralSecurityException {
    byte[] data = Base64.getDecoder().decode(key64);
    X509EncodedKeySpec spec = new X509EncodedKeySpec(data);
    KeyFactory fact = KeyFactory.getInstance("RSA");
    return fact.generatePublic(spec);
}

public static String publicKeyToStr(PublicKey publ) throws GeneralSecurityException {
    KeyFactory fact = KeyFactory.getInstance("RSA");
    X509EncodedKeySpec spec = fact.getKeySpec(publ, X509EncodedKeySpec.class);
    return Base64.getEncoder().encode(spec.getEncoded()).toString();
}

Crypto++:

using namespace CryptoPP;

RSAES_PKCS1v15_Decryptor priv(privString);
StringSource( cipher, cipherSize, true, new 
Base64Decoder( new PK_DecryptorFilter(randPool, priv, new StringSink(sdata))));

Upvotes: 1

Views: 2091

Answers (1)

vlp
vlp

Reputation: 8106

It is dangerous to use String instances for keeping binary data -- you should use byte[] instead.

Additionally, in the java code there is no Base64 wrapping of the resulting ciphertext, but in the C++ code it is being unwrapped from Base64.

Modified your code to return byte[] and encode the result using Base64:

public static byte[] encryptRSA(String str, PublicKey pubKey) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException, NoSuchProviderException {
    Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding", "BC");
    cipher.init(Cipher.ENCRYPT_MODE, pubKey);
    return cipher.doFinal(str.getBytes());
}

String cipher = Base64.getEncoder().encodeToString(Encryption.encryptRSA("0123456789ABCDEF", pubKeyk));

Then you can decrypt in Crypto++ the same way you did.

Good luck!

Upvotes: 1

Related Questions