使用PyCrypto的RSA公钥解密

时间:2013-10-23 17:47:25

标签: python rsa pycrypto

据我了解,我应该能够按照自己的意愿使用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的公钥解密?

2 个答案:

答案 0 :(得分:5)

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

您的应用程序需要签名,因此您不应该处理加密和解密。例如,PKCS#1 v1.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代码,以便创建这样的签名。

答案 1 :(得分:0)

你的功能是正确的。您只需要为其提供私钥的路径,以便解密而不是您的公钥。公钥用于加密,私钥用于解密。

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
相关问题