How do I use a X509 certificate with PyCrypto?(如何在 PyCrypto 中使用 X509 证书?)
问题描述
我想用 PyCrypto 在 python 中加密一些数据.
I want to encrypt some data in python with PyCrypto.
但是在使用 key = RSA.importKey(pubkey)
时出现错误:
However I get an error when using key = RSA.importKey(pubkey)
:
RSA key format is not supported
密钥是通过以下方式生成的:
The key was generated with:
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 证书.您必须首先使用以下命令提取公钥:
PyCrypto does not support X.509 certificates. You must first extract the public key with the command:
openssl x509 -inform pem -in mycert.pem -pubkey -noout > publickey.pem
然后,您可以在 publickey.pem
上使用 RSA.importKey
.
Then, you can use RSA.importKey
on publickey.pem
.
如果您不想或不能使用 openssl,您可以使用 PEM X.509 证书并在纯 Python 中这样做:
If you don't want or cannot use openssl, you can take the PEM X.509 certificate and do it in pure Python like this:
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)
这篇关于如何在 PyCrypto 中使用 X509 证书?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在 PyCrypto 中使用 X509 证书?


- 如何使用PYSPARK从Spark获得批次行 2022-01-01
- 我如何透明地重定向一个Python导入? 2022-01-01
- YouTube API v3 返回截断的观看记录 2022-01-01
- CTR 中的 AES 如何用于 Python 和 PyCrypto? 2022-01-01
- 使用公司代理使Python3.x Slack(松弛客户端) 2022-01-01
- 使用 Cython 将 Python 链接到共享库 2022-01-01
- ";find_element_by_name(';name';)";和&QOOT;FIND_ELEMENT(BY NAME,';NAME';)";之间有什么区别? 2022-01-01
- 我如何卸载 PyTorch? 2022-01-01
- 计算测试数量的Python单元测试 2022-01-01
- 检查具有纬度和经度的地理点是否在 shapefile 中 2022-01-01