esh*_*han 21 python openssl rsa pycrypto
我想用PyCrypto加密python中的一些数据.
但是我在使用时遇到错误key = RSA.importKey(pubkey):
RSA key format is not supported
Run Code Online (Sandbox Code Playgroud)
密钥生成时:
openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout mycert.key -out mycert.pem
Run Code Online (Sandbox Code Playgroud)
代码是:
def encrypt(data):
pubkey = open('mycert.pem').read()
key = RSA.importKey(pubkey)
cipher = PKCS1_OAEP.new(key)
return cipher.encrypt(data)
Run Code Online (Sandbox Code Playgroud)
Squ*_*ree 37
PyCrypto不支持X.509证书.您必须首先使用以下命令提取公钥:
openssl x509 -inform pem -in mycert.pem -pubkey -noout > publickey.pem
Run Code Online (Sandbox Code Playgroud)
然后,您可以使用RSA.importKey上publickey.pem.
如果您不想或不能使用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)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
26879 次 |
| 最近记录: |