据我所知,我应该能够使用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对公钥进行解密?
发布于 2013-10-23 20:37:06
这是完全不安全的,因为您使用的是未填充的原始RSA。
您的应用程序需要一个签名,所以您不应该处理加密和解密。例如,PKCS#1 v1.5是一个很好的协议,尽管签名是一个必须附加到您想要证明其真实性的数据。
要在Pythonv1.5中验证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代码,以便创建这样的签名。
发布于 2013-11-20 04:07:16
你的功能是正确的。您只需要给它路径到您的私钥,以便解密,而不是您的公钥。公钥用于加密,私钥用于解密。
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
https://stackoverflow.com/questions/19548800
复制相似问题