python - 如何在 PyCrypto 中使用 X509 证书?

标签 python openssl rsa pycrypto

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

但是在使用 key = RSA.importKey(pubkey) 时出现错误:

RSA key format is not supported

key 是通过以下方式生成的:

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

然后,您可以在 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)

关于python - 如何在 PyCrypto 中使用 X509 证书?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12911373/

相关文章:

python - (RSA)我从 stackoverflow 得到的这个脚本返回负 d 值

python - 如何将旧的 python 代码从 m2crypto 迁移到密码学(摘要的 RSA 签名)

python - Pandas DataFrame .style.format 不工作

c - X509_STORE_add_lookup() 中的段错误

qt - 使用QSslSocket时无法解析的功能

java - 使用java进行RSA解密失败

python - 在 PySide2 中为 QML 注册枚举

python - 具有对角权重矩阵的自定义层

linux - 在 .so 文件中更新动态链接的 .so 文件和在 .so 文件中更新静态链接的 .a 文件

c++ - 第二次调用 RSA_private_decrypt 时崩溃