【发布时间】:2016-01-08 05:04:25
【问题描述】:
我正在尝试使用 Java 中的 RSA 公钥加密数据并使用 Crypto++ 对其进行解密。这会导致错误:
“RSA/EME-PKCS1-v1_5:24 的密文长度与此密钥所需的 128 长度不匹配”
我做错了什么?
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();
}
加密++:
using namespace CryptoPP;
RSAES_PKCS1v15_Decryptor priv(privString);
StringSource( cipher, cipherSize, true, new
Base64Decoder( new PK_DecryptorFilter(randPool, priv, new StringSink(sdata))));
【问题讨论】:
-
byte[] encryptedAesKey = cipher.doFinal(str.getBytes()); String cipherStr = new String(encryptedAesKey);这没有机会工作,根本没有意义。 -
“我做错了什么……” - 我们需要看看你如何在 Java 中保存密文,以及如何在 Crypto++ 中加载它。我的猜测是所有密文 not 都是用 Java 编写的,或者所有密文 not 都是用 Crypto++ 加载的。小心 C++
std::string。一些构造函数在第一个NULL字符处停止。 -
一切都好吗?你如何解决这个问题?
标签: java c++ interop rsa crypto++