使用 pycrypto,如何导入 RSA 公钥并使用它来加密字符串? [英] Using pycrypto, how to import a RSA public key and use it to encrypt a string?
问题描述
RSA 公钥:
PUBKEY = 'MIGfMA0GCSqGSIb3DQEBA3UAA4GNADCBiQKBgQC35eMaYoJXEoJt5HxarHkzDBEMU3qIWE0HSQ77CwP/8UbX07W2XKwngUyY4k6Hl2M/n9TOZMZsiBzer/fqV + QNPN1m9M94eUm2gQgwkoRj5battRCaNJK/23GGpCsTQatJN8PZBhJBb2Vlsvw5lFrSdMT1R7vaz + 2EeNR/FitFXwIDAQAB'
pubkey = 'MIGfMA0GCSqGSIb3DQEBA3UAA4GNADCBiQKBgQC35eMaYoJXEoJt5HxarHkzDBEMU3qIWE0HSQ77CwP/8UbX07W2XKwngUyY4k6Hl2M/n9TOZMZsiBzer/fqV+QNPN1m9M94eUm2gQgwkoRj5battRCaNJK/23GGpCsTQatJN8PZBhJBb2Vlsvw5lFrSdMT1R7vaz+2EeNR/FitFXwIDAQAB'
如何导入并使用它来加密字符串?
how to import it and use it to encrypt a string?
我尝试了以下代码,但 RSA.construct() 引发异常(TypeError: must be long, not str).
I tried the following code but RSA.construct() raises exception (TypeError: must be long, not str).
from Crypto.PublicKey import RSA
from Crypto.Util import asn1
from base64 import b64decode
keyDER = b64decode(pubkey)
seq = asn1.DerSequence()
seq.decode(keyDER)
keyPub = RSA.construct((seq[0], seq[1]))
print keyPub.encrypt('mysecret', 32)
谢谢.
推荐答案
我也遇到了这个问题.我让它像这样工作:
I too had trouble with this. I got it working like this:
key = RSA.generate(2048)
binPrivKey = key.exportKey('DER')
binPubKey = key.publickey().exportKey('DER')
privKeyObj = RSA.importKey(binPrivKey)
pubKeyObj = RSA.importKey(binPubKey)
msg = "attack at dawn"
emsg = pubKeyObj.encrypt(msg, 'x')[0]
dmsg = privKeyObj.decrypt(emsg)
assert(msg == dmsg)
如果您正在写入文件,您可能会发现处理十六进制字符串比处理二进制字符串更容易.我经常使用这些辅助函数
If you're writing to files, you may find it easier to deal with hex strings instead of binary strings. I'm using these helper functions a lot
def bin2hex(binStr):
return binascii.hexlify(binStr)
def hex2bin(hexStr):
return binascii.unhexlify(hexStr)
这篇关于使用 pycrypto,如何导入 RSA 公钥并使用它来加密字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!