我想用PyCrypto在python中加密一些数据。
但是使用时出现错误key = RSA.importKey(pubkey):
key = RSA.importKey(pubkey)
RSA key format is not supported
密钥是使用以下命令生成的:
openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout mycert.key -out mycert.pem
代码是:
def encrypt(data): pubkey = open('mycert.pem').read() key = RSA.importKey(pubkey) cipher = PKCS1_OAEP.new(key) return cipher.encrypt(data)
PyCrypto不支持X.509证书。您必须首先使用以下命令提取公钥:
openssl x509 -inform pem -in mycert.pem -pubkey -noout > publickey.pem
然后,您可以RSA.importKey在上使用publickey.pem。
RSA.importKey
publickey.pem
如果您不想或不能使用openssl,则可以获取PEM X.509证书,并使用纯Python进行认证,如下所示:
from Crypto.Util.asn1 import DerSequence from Crypto.PublicKey import RSA from binascii import a2b_base64 # Convert from PEM to DER pem = open("mycert.pem").read() lines = pem.replace(" ",'').split() der = a2b_base64(''.join(lines[1:-1])) # Extract subjectPublicKeyInfo field from X.509 certificate (see RFC3280) cert = DerSequence() cert.decode(der) tbsCertificate = DerSequence() tbsCertificate.decode(cert[0]) subjectPublicKeyInfo = tbsCertificate[6] # Initialize RSA key rsa_key = RSA.importKey(subjectPublicKeyInfo)