2012-10-16 74 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)