使用带有PyCryp的RSA公钥解密

2024-09-28 21:15:30 发布

您现在位置:Python中文网/ 问答频道 /正文

据我所知,我应该能够使用RSA来确保真实性或隐私,如我所愿。在我的例子中,我想确保真实性,所以我用私钥加密数据,并允许任何人用公钥解密。数据不是真正的秘密,但我需要保证它是由公钥(和私钥)所有者创建的。

当我尝试使用PyCrypto解密时,我从PyCrypto得到没有私钥错误。代码如下:

def _decrypt_rsa(decrypt_key_file, cipher_text):
    from Crypto.PublicKey import RSA
    from base64 import b64decode

    key = open(decrypt_key_file, "r").read()
    rsakey = RSA.importKey(key)
    raw_cipher_data = b64decode(cipher_text)
    decrypted = rsakey.decrypt(raw_cipher_data)
    return decrypted

我用公钥文件的路径(OpenSSH格式)调用它。加密的数据不是我生成的,不是用Python而是PHP完成的。在PHP中,有一个openssl_public_decrypt函数可以轻松地解密这些数据。

使用带有PyCrypto的公钥可以解密吗?


Tags: 数据keytextfromimportrsafile真实性
2条回答

你的功能是正确的。你只需要给它你的私钥的路径,以便解密而不是你的公钥。公钥用于加密,私钥用于解密。

def _decrypt_rsa(decrypt_key_file, cipher_text):
    '''
    Decrypt RSA encrypted package with private key
    :param decrypt_key_file: Private key
    :param cipher_text: Base64 encoded string to decrypt
    :return: String decrypted
    '''
    from Crypto.PublicKey import RSA
    from base64 import b64decode

    key = open(decrypt_key_file, "r").read()
    rsakey = RSA.importKey(key)
    #optionally could use OAEP
    #from Crypto.Cipher import PKCS1_OAEP
    #rsakey = PKCS1_OAEP.new(rsakey)
    raw_cipher_data = b64decode(cipher_text)
    decrypted = rsakey.decrypt(raw_cipher_data)
    return decrypted

这是完全不安全的,因为您使用的是没有填充的原始RSA。

您的应用程序需要签名,因此不应处理加密和解密。例如,PKCS#1v1.5是一个很好的协议,即使签名是一段必须附加到要证明其真实性的数据。

要在Python中验证PKCS#1 v1.5签名,请执行以下操作:

from Crypto.PublicKey import RSA
from Crypto.Signature import PKCS1_v1_5
from Crypto.Hash import SHA

rsa_key = RSA.importKey(open(verification_key_file, "rb").read())
verifier = PKCS1_v1_5.new(rsa_key)
h = SHA.new(data_to_verify)
if verifier.verify(h, signature_received_with_the_data):
    print "OK"
else:
    print "Invalid"

我强烈建议更改PHP代码,以便它创建这样的签名。

相关问题 更多 >