c++ - Encrypt data with RSA public key in Java and decrypt in Crypto++ -
i'm trying encrypt data rsa public key in java , decrypt in crypto++. results in error:
"rsa/eme-pkcs1-v1_5: ciphertext length of 24 doesn't match required length of 128 key"
what 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))));
it dangerous use string instances keeping binary data -- should use byte[] instead.
additionally, in java code there no base64 wrapping of resulting ciphertext, in c++ code being unwrapped base64.
modified code return byte[] , encode 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 can decrypt in crypto++ same way did.
good luck!
Comments
Post a Comment