从证书中提取公钥并加密数据

时间:2011-04-26 10:48:05

标签: python network-programming rsa pyopenssl

这是作业作业! 我使用get_peer_certificate()获取服务器的证书 并调用dump_certificate将证书转储到变量中。格式是PEM,看起来对我来说。

-----BEGIN CERTIFICATE-----
GIBBERISH................
......................
........................

-----END CERTIFICATE-----

如何从此文件中提取服务器的公钥('server.pubkey')并使用plaintext算法和任何python库加密RSA。在撰写本文时,我正在使用pyOpenSSL

2 个答案:

答案 0 :(得分:5)

我建议使用更广泛的crypto library such as M2Crypto,它具有X509证书功能以及RSA加密功能:

from M2Crypto import RSA, X509
data = ssl_sock.getpeercert(1)
# load the certificate into M2Crypto to manipulate it
cert = X509.load_cert_string(data, X509.FORMAT_DER)
pub_key = cert.get_pubkey()
rsa_key = pub_key.get_rsa()
cipher = rsa_key.public_encrypt('plaintext', RSA.pkcs1_padding)

答案 1 :(得分:3)

    crtObj = crypto.load_certificate(crypto.FILETYPE_ASN1, config.x509_certificate)
    pubKeyObject = crtObj.get_pubkey()
    pubKeyString = crypto.dump_publickey(crypto.FILETYPE_PEM, pubKeyObject)