【问题标题】:Encrypt data with RSA public key in Java and decrypt in Crypto++在 Java 中使用 RSA 公钥加密数据并在 Crypto++ 中解密
【发布时间】: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++


【解决方案1】:

使用 String 实例来保存二进制数据是很危险的——你应该使用 byte[] 来代替。

此外,在 java 代码中没有对生成的密文进行 Base64 包装,但在 C++ 代码中,它是从 Base64 解包的。

修改您的代码以返回 byte[] 并使用 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));

然后你可以像以前一样在 Crypto++ 中解密。

祝你好运!

【讨论】:

    猜你喜欢
    • 2021-01-15
    • 2020-02-28
    • 1970-01-01
    • 2018-01-09
    • 1970-01-01
    • 1970-01-01
    • 2011-03-08
    • 2010-10-25
    • 1970-01-01
    相关资源
    最近更新 更多