使用带有 PyCrypto 的 RSA 公钥解密 [英] Decrypt using an RSA public key with PyCrypto

查看:54
本文介绍了使用带有 PyCrypto 的 RSA 公钥解密的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

据我所知,我应该能够如我所愿地使用 RSA 来确保真实性或隐私.就我而言,我想确保真实性,因此我使用私钥对数据进行加密,并允许任何人使用公钥对其进行解密.数据并不是真正的秘密,但我需要保证它是由公钥(和私钥)的所有者创建的.

As far as I understand, I should be able to use RSA to ensure authenticity or privacy, as I wish. In my case, I want to ensure authenticity so I encrypt the data with the private key and allow anyone to decrypt it with the public key. The data is not really secret but I need to guarantee that it was created by the owner of the public (and private) key.

当我尝试使用 PyCrypto 解密时,我收到来自 PyCrypto 的没有私钥错误.代码是这样的:

When I try to decrypt using PyCrypto I get No private key error from PyCrypto. The code is this:

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 函数可以轻松解密这些数据.

I'm calling it with the path to the public key file (in OpenSSH format.) The encrypted data isn't generated by me and it was not done with Python but PHP. In PHP there's a openssl_public_decrypt function that decrypts this data easily.

是否有可能使用 PyCrypto 的公钥进行解密?

Is it possible at all to decrypt using the public key with PyCrypto?

推荐答案

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

That is totally insecure, because you are using raw RSA without padding.

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

Your application needs a signature, so you should not be dealing with encryptions and decryptions. For instance, PKCS#1 v1.5 is a good protocol, even though the signature is a piece of data that must be appended to what you want to prove the authenticity of.

要在 Python 中验证 PKCS#1 v1.5 签名,您可以:

To verify a PKCS#1 v1.5 signature in Python, you do:

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 代码以创建这样的签名.

I would strongly recommend to change the PHP code so that it creates such a signature.

这篇关于使用带有 PyCrypto 的 RSA 公钥解密的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆