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 证书?
基础教程推荐
- 使用大型矩阵时禁止 Pycharm 输出中的自动换行符 2022-01-01
- 求两个直方图的卷积 2022-01-01
- 包装空间模型 2022-01-01
- 在Python中从Azure BLOB存储中读取文件 2022-01-01
- 在同一图形上绘制Bokeh的烛台和音量条 2022-01-01
- Plotly:如何设置绘图图形的样式,使其不显示缺失日期的间隙? 2022-01-01
- 无法导入 Pytorch [WinError 126] 找不到指定的模块 2022-01-01
- 修改列表中的数据帧不起作用 2022-01-01
- PANDA VALUE_COUNTS包含GROUP BY之前的所有值 2022-01-01
- PermissionError: pip 从 8.1.1 升级到 8.1.2 2022-01-01
