简体   繁体   English

如何在PyCrypto中使用X509证书?

[英]How do I use a X509 certificate with PyCrypto?

I want to encrypt some data in python with PyCrypto. 我想用PyCrypto加密python中的一些数据。

However I get an error when using key = RSA.importKey(pubkey) : 但是,当使用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

The code is: 代码是:

def encrypt(data):
    pubkey = open('mycert.pem').read()
    key = RSA.importKey(pubkey)
    cipher = PKCS1_OAEP.new(key)
    return cipher.encrypt(data)

PyCrypto does not support X.509 certificates. PyCrypto不支持X.509证书。 You must first extract the public key with the command: 您必须首先使用以下命令提取公钥:

openssl x509 -inform pem -in mycert.pem -pubkey -noout > publickey.pem

Then, you can use RSA.importKey on publickey.pem . 然后,您可以在publickey.pem上使用RSA.importKey


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: 如果您不想或不能使用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)

Here's a good example: https://www.dlitz.net/software/pycrypto/api/2.6/Crypto.Cipher.PKCS1_OAEP-module.html 这是一个很好的例子: https//www.dlitz.net/software/pycrypto/api/2.6/Crypto.Cipher.PKCS1_OAEP-module.html

from Crypto.Cipher import PKCS1_OAEP
from Crypto.PublicKey import RSA

# sender side
message = 'To be encrypted'
key = RSA.importKey(open('pubkey.der').read())
cipher = PKCS1_OAEP.new(key)
ciphertext = cipher.encrypt(message)

# receiver side
key = RSA.importKey(open('privkey.der').read())
cipher = PKCS1_OAP.new(key)
message = cipher.decrypt(ciphertext)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM