JSEncrypt 到 PyCrypto RSA 加密不可能

JSEncrypt to PyCrypto RSA encryption not possible

我正在尝试使用 RSA(public 密钥)加密 Javascript 中的字符串 我想用我的私钥解密 Python (2.7) 中的那个字符串。

我使用的库是 JSEncrypt 和 PyCrypto 这里的问题是,PyCrypto 在解密加密字符串时有问题

这部分加密字符串:

var encrypted = new JSEncrypt();
encrypted.setPublicKey(key); // key == '-----BEGIN PUBLIC'.....
encrypted = encrypted.encrypt('test');

生成的加密字符串如下所示: HJuyZtuUbR4EvjZp0pirbEw0OX8KD7UDNyvSMx3plfzYPjV7r8RBOkouCkvPBG2XOF6E5lPr0ukWClF0u5HB8M6qF8b9xTMnM/j5e41iaPa/oIZyL0JC4h+FZ7cv/P6ygmaSafQ1xc96JltTbuW3u/YYdwmv/01CnFyaIEWW3gk=

这部分应该解密:

private_rsa_key = open('rsa_1024_priv.pem', 'r').read()
rsa_key = RSA.importKey(private_rsa_key)
decrypted = rsa_key.decrypt(b64decode(encrypted_string))

现在的结果应该是'test',但确实是:

正确的字符串总是放在最后,但我需要去掉它前面的部分。

出于测试目的,我尝试使用以下代码加密 Python 中的字符串:

public_rsa_key = open('rsa_1024_pub.pem', 'r').read()
rsa_key = RSA.importKey(public_rsa_key)
encrypted = rsa_key.encrypt('test', 'x')

解密时完美 'test',但加密后看起来完全不同:

('\x0bY\x1ckk\x7f\xd6\xda$\x05g\xa0\x0bxI\x0cO9\x8b?>M#X\xd2_[\xb7\xf1\xd0f\xb4\x92C\x01z\xa4\x02q\xb9\xb1\x80\x82\xe8\xe4\E\x85\xa7r\xff\x1aIL,\xd8\xce\xaf\xef\xb4)\x84\x92]\xabA\xc9+\xd6\xef}\x08\xce\xe8\x97\xf8}\x84(\xb3\x9c\xfe7g\xe0\x869\x8b\xe8\xf8\xdf\x85}\xb0\x87\x1a2\xab\xda\xca\xfd\x81\xc0\x98\x12y\x92\x13\xd6\xa5a\xf3\x9aU\xb5\xa4d\xb8\xfc\xa3\xd1\xe2<\x07\xda\xc3\x9e\xc2',)

我想知道为什么这个加密文本现在是一个元组,里面有十六进制。在我看来,来自 JS 的加密字符串看起来是正确的。我怎样才能让 PyC​​rypto 正确解密字符串?

提前致谢

您发布的 python 代码仅进行低级解密,jsencrypt 返回的加密数据也 contains pkcs1 padding

您需要使用适当的 cipher, in this case PKCS1_v1_5:

,而不是在您的 python 代码中使用 encrypt/decrypt 的原始 RSA 密钥
...
from Crypto.Cipher import PKCS1_v1_5
private_rsa_key = open('rsa_1024_priv.pem', 'r').read()
rsa_key = RSA.importKey(private_rsa_key)
cipher = PKCS1_v1_5.new(rsa_key)
decrypted = cipher.decrypt(encrypted, "ERROR")

使用 public 密钥加密时也是如此。