我试图解密使用RSA-OAEP在Golang中加密的字符串。但得到BadPaddingException:解密错误。很难弄清楚我错过了什么..
这是Golang加密方法
func encryptString() {
rootPEM := io_related.ReadFile("../../resources/pubkey.pem")
//fmt.Printf("Cert String %q \n", rootPEM)
block, _ := pem.Decode([]byte(rootPEM))
var cert *x509.Certificate
cert, _ = x509.ParseCertificate(block.Bytes)
rsaPublicKey := cert.PublicKey.(*rsa.PublicKey)
secretMessage := []byte("password")
label := []byte("")
// crypto/rand.Reader is a good source of entropy for randomizing the
// encryption function.
rng := rand.Reader
ciphertext, err := rsa.EncryptOAEP(sha256.New(), rng, rsaPublicKey, secretMessage, label)
if err != nil {
fmt.Fprintf(os.Stderr, "Error from encryption: %s\n", err)
return
}
// Since encryption is a randomized function, ciphertext will be
// different each time.
base64EncodedString := base64.StdEncoding.EncodeToString(ciphertext)
fmt.Println(base64EncodedString)
}
和我的java解密方法
public void decryptString(String base64String) throws NoSuchAlgorithmException, CertificateException, IOException, KeyStoreException, UnrecoverableKeyException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException{
FileInputStream is = new FileInputStream("priv.p12");
KeyStore keystore = KeyStore.getInstance("PKCS12");
keystore.load(is, "".toCharArray());
System.out.println("Successfully loaded");
String keyAlias = "1";
PrivateKey key = (PrivateKey)keystore.getKey(keyAlias, "".toCharArray());
System.out.println("key "+Base64.encodeBase64String(key.getEncoded()));
Cipher rsaDecryptCipher;
rsaDecryptCipher = Cipher.getInstance("RSA/ECB/OAEPWITHSHA-256ANDMGF1PADDING");
rsaDecryptCipher.init(Cipher.DECRYPT_MODE, key);
final byte[] plainText = rsaDecryptCipher.doFinal(Base64.decodeBase64(base64String));
System.out.println("Plain : " + new String(plainText));
}
我可能遗漏了一些东西,如果有人需要更多细节,请告诉我。感谢帮助!!感谢
答案 0 :(得分:0)
OAEP使用两种哈希算法:一种在标签上(fka参数),一种在掩码生成功能(MGF1)内;这些可以是不同的。见rfc8017中的7.1.1和B.2.1。
我不知道Go代码是设置一个(以及哪个)或两者,但Java对getInstance
的影响取决于您使用的提供商,这反过来至少部分取决于你正在使用什么Java实现。 Sun / Oracle和OpenJDK实现中默认配置的SunJCE提供程序仅更改标签哈希,将MGF1保持为SHA1; BouncyCastle提供商改变了两者。我不知道IBM和Android在这里做了什么。
一旦您确定(或猜测)Go正在做什么,您可以通过在.init
电话中添加适当的OAEPParameterSpec
和相关的MGF1ParameterSpec
来匹配它。
主要是欺骗OAEPwithMD5andMGF1Padding in node-rsa
和breaking down RSA/ECB/OAEPWITHSHA-256ANDMGF1PADDING
(复制于https://security.stackexchange.com/questions/97548/breaking-down-rsa-ecb-oaepwithsha-256andmgf1padding)