2012-10-16 13 views
16

Voglio crittografare alcuni dati in python con PyCrypto.Come utilizzare un certificato X509 con PyCrypto?

Tuttavia ho un errore quando si utilizza key = RSA.importKey(pubkey):

RSA key format is not supported 

La chiave è stata generata con:

openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout mycert.key -out mycert.pem 

Il codice è:

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

prima risposta in una ricerca su Google: http://stackoverflow.com/questions/10569189/how-to-read-a-rsa-public-key-in-pem-pkcs1-format-in-python – tMC

+0

@ tMC non funziona con me, io uso certificat e, non un file di chiave pubblica. – eshizhan

risposta

31

pycrypto non supporta X. 509 certificati. È innanzitutto necessario estrarre la chiave pubblica con il comando:

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

Quindi, è possibile utilizzare RSA.importKey su publickey.pem.


Se non si vuole o non può usare OpenSSL, si può prendere il certificato X.509 PEM e lo fa in puro Python come questo:

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) 
+9

Come nota, la conversione PEM-> DER può essere eseguita più facilmente utilizzando builtin ['ssl.PEM_cert_to_DER_cert()'] (http://docs.python.org/2/library/ssl.html#ssl.PEM_cert_to_DER_cert). –

+0

Puoi spiegare come crittare una stringa dopo questo passaggio? –

+0

è ancora il caso nel 2016? –

1

Ecco un buon esempio: 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) 
Problemi correlati