2012-10-16 71 views
16

我想用PyCrypto加密python中的一些數據。如何在PyCrypto中使用X509證書?

但是我使用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) 
+0

在谷歌搜索首度迴應:http://stackoverflow.com/questions/10569189/how-to-read-a-rsa-public-key-in-pem-pkcs1-format-in-python – tMC

+0

@tMC不適用於我,我使用certificat e,而不是公鑰文件。 – eshizhan

回答

31

PyCrypto不支持X. 509份證書。你必須先用命令提取公鑰:

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

然後,您可以在publickey.pem使用RSA.importKey


如果你不想或者不能使用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) 
+9

注意,使用內建['ssl.PEM_cert_to_DER_cert()'](http://docs.python.org/2/library/ssl.html#ssl.PEM_cert_to_DER_cert)可以更輕鬆地完成PEM-> DER轉換。 –

+0

你能解釋一下在這一步之後如何隱藏一個字符串嗎? –

+0

2016年情況如何? –

1

這裏有一個很好的例子: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)