如何在 PyCrypto 中使用 X509 证书? [英] How do I use a X509 certificate with PyCrypto?

查看:23
本文介绍了如何在 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 证书?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆