如何在PyCrypto中使用X509证书?

时间:2012-10-16 09:18:48

标签: python openssl rsa pycrypto

我想用PyCrypto加密python中的一些数据。

但是在使用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)

2 个答案:

答案 0 :(得分:36)

PyCrypto不支持X.509证书。您必须首先使用以下命令提取公钥:

openssl x509 -inform pem -in mycert.pem -pubkey -noout > 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)

答案 1 :(得分:1)

以下是一个很好的例子:https://www.dlitz.net/software/pycrypto/api/2.6/Crypto.Cipher.PKCS1_OAEP-module.html

from Crypto.Cipher import PKCS1_OAEP
from Crypto.PublicKey import RSA

# sender side
message = 'To be encrypted'
key = RSA.importKey(open('pubkey.der').read())
cipher = PKCS1_OAEP.new(key)
ciphertext = cipher.encrypt(message)

# receiver side
key = RSA.importKey(open('privkey.der').read())
cipher = PKCS1_OAP.new(key)
message = cipher.decrypt(ciphertext)