【问题标题】:How do I use a X509 certificate with PyCrypto?如何在 PyCrypto 中使用 X509 证书?
【发布时间】:2012-10-06 08:33:30
【问题描述】:

我想用 PyCrypto 在 python 中加密一些数据。

但是在使用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)

【问题讨论】:

标签: python openssl rsa pycrypto


【解决方案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)

【讨论】:

    【解决方案2】:

    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)
    

    【讨论】:

    • 请注意,使用内置ssl.PEM_cert_to_DER_cert() 可以更轻松地完成 PEM->DER 转换。
    • 你能解释一下在这一步之后如何加密一个字符串吗?
    • 2016年还是这样吗?
    • 2016年可以使用pycryptodome,可以直接用importKey读入X.509证书。
    • 任何人都需要自行验证 google oauth 令牌,因为他们发布的公钥是 x509 证书googleapis.com/oauth2/v1/certs
    猜你喜欢
    • 1970-01-01
    • 2011-04-06
    • 2015-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多