Как использовать сертификат X509 с PyCrypto? - программирование
Подтвердить что ты не робот

Как использовать сертификат X509 с PyCrypto?

Я хочу зашифровать некоторые данные в python с помощью PyCrypto.

Однако я получаю сообщение об ошибке при использовании key = RSA.importKey(pubkey):

RSA key format is not supported

Ключ был сгенерирован с помощью:

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)
4b9b3361

Ответ 1

PyCrypto не поддерживает сертификаты X.509. Вы должны сначала извлечь открытый ключ с помощью команды:

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

Затем вы можете использовать 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)

Ответ 2

Вот хороший пример: 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)