如何在PyCrypto中使用X509证书?

24

我想使用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)

谷歌搜索的第一个回答:https://dev59.com/F2kv5IYBdhLWcg3wewxd - tMC
@tMC对我不起作用,我使用证书而不是公钥文件。 - eshizhan
2个回答

39

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

openssl x509 -inform pem -in mycert.pem -pubkey -noout > publickey.pem

然后,您可以在publickey.pem上使用RSA.importKey


如果您不想或无法使用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)

9
作为提醒,可以使用内置的 ssl.PEM_cert_to_DER_cert() 更轻松地进行 PEM->DER 转换。 - Michał Górny
你能解释一下在这一步之后如何加密一个字符串吗? - Pierluigi B Web Developer
2016年还是这种情况吗? - allan.simon
2016年,我们可以使用pycryptodome直接使用“importKey”读取X.509证书。 - SquareRootOfTwentyThree
这是任何需要验证自己的Google OAuth令牌的人所必需的,因为它们发布的公钥是x509证书,https://www.googleapis.com/oauth2/v1/certs。 - casey

2
这是一个很好的例子: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_OAEP.new(key)
message = cipher.decrypt(ciphertext)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接