Python 如何在 PyCrypto 中使用 X509 证书?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12911373/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I use a X509 certificate with PyCrypto?
提问by eshizhan
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)
采纳答案by SquareRootOfTwentyThree
PyCrypto does not support X.509 certificates. You must first extract the public key with the command:
PyCrypto 不支持 X.509 证书。您必须首先使用以下命令提取公钥:
openssl x509 -inform pem -in mycert.pem -pubkey -noout > publickey.pem
Then, you can use RSA.importKeyon publickey.pem.
然后,您可以RSA.importKey在publickey.pem.
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)
回答by earthling
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)

