无法使用开放SSL解密RSA数据

我尝试使用openssl创建的公钥在matlab中加密一些数据

我用以下方法创建了密钥:

openssl genrsa -des3 -out private.pem 1024 openssl rsa -in private.pem -pubout -outform DER -out public.der 

我使用这个matlab代码(使用Java库)加密我的数据:

 import java.security.spec.RSAPublicKeySpec import javax.crypto.Cipher; import java.security.KeyFactory import java.math.BigInteger fid = fopen('public.der'); a = fread(fid); key = java.security.spec.X509EncodedKeySpec(a); kf = KeyFactory.getInstance('RSA'); KEY = kf.generatePublic(key); cipher = Cipher.getInstance('RSA/ECB/PKCS1Padding'); cipher.init(Cipher.ENCRYPT_MODE, KEY) plaintextBytes = [24]; ciphertext = cipher.doFinal(plaintextBytes)' ; fid2 = fopen('msg.txt','w'); fwrite(fid2,ciphertext); fclose(fid2); 

我尝试使用以下方法解密它:

 openssl rsautl -decrypt -inkey private.pem -in msg.txt -keyform PEM -pkcs 

然后我收到这个错误:

 RSA operation error 80305:error:0407109F:rsa routines:RSA_padding_check_PKCS1_type_2:pkcs decoding error:/BuildRoot/Library/Caches/com.apple.xbs/Sources/OpenSSL098/OpenSSL098-59.40.2/src/crypto/rsa/rsa_pk1.c:267: 80305:error:04065072:rsa routines:RSA_EAY_PRIVATE_DECRYPT:padding check failed:/BuildRoot/Library/Caches/com.apple.xbs/Sources/OpenSSL098/OpenSSL098-59.40.2/src/crypto/rsa/rsa_eay.c:614: 

大多数情况下,这样的“RSA_padding_check_PKCS1_type_2错误……” – 你倾向于看到这一点(1)编码错误:不是解密二进制数据,而是对(可能)Base64编码数据进行解密。 (2)密钥对或密钥本身不匹配:公钥与私钥不匹配以进行解密。 http://hustoknow.blogspot.ca/2013/01/rsa-block-type-is-not-02-error.html

也许我们可以在说密码加载不正确之前确保该对不匹配(2)(1)。 如下面参考https://www.sslshopper.com/ssl-converter.html

将PEM转换为DER:openssl x509 -outform der -in certificate.pem -out certificate.der或者如果证书已经是“der”格式,也可以变成“pem”,例如将DER转换为PEM:openssl x509 -inform der -in certificate.cer -out certificate.pem

将PEM转换为PFX:openssl pkcs12 -export -out certificate.pfx -inkey privateKey.key -in certificate.crt -certfile CACert.crt或者如果只有“pfx”则可以获得“pem”,例如将PFX转换为PEM:openssl pkcs12 -in certificate.pfx -out certificate.cer -nodes

在确定我们有“pem”之后,我们可以尝试加密和解密,如http://openssl.6102.n7.nabble.com/unable-to-decrypt-using-using-private-key-td15204中所述。 HTML

例如1)openssl enc -base64 -d -in -out创建的地方,它有二进制内容。 例如2)openssl rsautl -decrypt -inkey -out -pkcs但在这种情况下,考虑尝试使用-raw而不是-pkcs来解密带有服务器私钥的数据