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 证书?
基础教程推荐
- 在 Python 中将货币解析为数字 2022-01-01
- Python 中是否有任何支持将长字符串转储为块文字或折叠块的 yaml 库? 2022-01-01
- 究竟什么是“容器"?在蟒蛇?(以及所有的 python 容器类型是什么?) 2022-01-01
- Kivy 使用 opencv.调整图像大小 2022-01-01
- Python,确定字符串是否应转换为 Int 或 Float 2022-01-01
- kivy 应用程序中的一个简单网页作为小部件 2022-01-01
- 在 Django Admin 中使用内联 OneToOneField 2022-01-01
- 比较两个文本文件以找出差异并将它们输出到新的文本文件 2022-01-01
- 对多索引数据帧的列进行排序 2022-01-01
- matplotlib 设置 yaxis 标签大小 2022-01-01
