我有一个用例,我想用c中的私钥加密一些数据,用java中的公钥解密它。
我使用openssl生成了公钥/私钥。我可以运行一个c代码来使用私钥加密数据。
类似于以下代码:
# include <openssl/pem.h>
# include <openssl/ssl.h>
# include <openssl/rsa.h>
# include <openssl/evp.h>
# include <openssl/bio.h>
# include <openssl/err.h>
int padding = RSA_PKCS1_PADDING;
char * data;
char *encrypted;
FILE * fp = fopen(<private_key_file>,"rb");
RSA *rsa= RSA_new() ;
rsa = PEM_read_RSAPrivateKey(fp, &rsa,NULL, NULL);
RSA_private_encrypt(data_len,data,encrypted,rsa,padding);
这工作得很好,我也可以用c中的公钥解密它。我不能用java中的公钥解密相同的密码。为此,我将公钥转换为der格式: $ openssl rsa -in private_key.pem -pubout -outform DER -out public_key.der
我使用以下代码
public String decrypt(byte[] encrypted) throws Exception
{
Cipher cipher = Cipher.getInstance("RSA");
KeyFactory kf = KeyFactory.getInstance("RSA");
byte[] encKey = readFromFile(PUBLIC_KEY_FILE, false);
X509EncodedKeySpec ks = new X509EncodedKeySpec(encKey);
PublicKey pk = kf.generatePublic(ks);
cipher.init(Cipher.DECRYPT_MODE, pk);
byte[] plainText = cipher.doFinal(encrypted);
return new String(plainText,"UTF-8");
}
我的java代码有以下异常。
Exception in thread "main" javax.crypto.BadPaddingException: Decryption error
at sun.security.rsa.RSAPadding.unpadV15(RSAPadding.java:380)
at sun.security.rsa.RSAPadding.unpad(RSAPadding.java:291)
at com.sun.crypto.provider.RSACipher.doFinal(RSACipher.java:356)
at com.sun.crypto.provider.RSACipher.engineDoFinal(RSACipher.java:389)
at javax.crypto.Cipher.doFinal(Cipher.java:2121)
at AssyncKeyEncryptTest.decrypt(AssyncKeyEncryptTest.java:198)
at AssyncKeyEncryptTest.test(AssyncKeyEncryptTest.java:45)
at AssyncKeyEncryptTest.main(AssyncKeyEncryptTest.java:32)
有人能帮我解决在java中使用公钥解密数据的错误吗?
2条答案
按热度按时间voase2hg1#
尝试
"RSA/None/PKCS1Padding"
而不是"RSA"
. 如果你找不到Cipher
示例"RSA/None/PKCS1Padding"
然后尝试添加像bouncy castle provider这样的安全提供程序。Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
添加bouncy castle依赖项应该足够简单。http://www.bouncycastle.org/latest_releases.html
o0lyfsai2#
stacktrace建议在加密和解密之间使用不同的填充。
在加密时使用“pkcs1padding”作为解密示例。