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

Lel*_*uge 3 python network-programming rsa pyopenssl

这是一个家庭作业!我使用服务器的证书get_peer_certificate() 和调用dump_certificate将证书转储到变量中.格式是PEM,看起来对我来说.

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

-----END CERTIFICATE-----
Run Code Online (Sandbox Code Playgroud)

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

小智 6

    from OpenSSL import crypto        
    crtObj = crypto.load_certificate(crypto.FILETYPE_ASN1, config.x509_certificate)
    pubKeyObject = crtObj.get_pubkey()
    pubKeyString = crypto.dump_publickey(crypto.FILETYPE_PEM, pubKeyObject)
Run Code Online (Sandbox Code Playgroud)


sam*_*ias 5

我建议使用更广泛的加密库,如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)
Run Code Online (Sandbox Code Playgroud)