pythonnetwork-programmingrsapyopenssl

extracting public key from certificate and encrypting data


This is for a homework assignment! I get the server's certificate using get_peer_certificate() and the calling dump_certificate to dump the certificate in a variable. The format is PEM and looks right to me.

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

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

How do I extract the server's public key from this file ('server.pubkey') and encrypt plaintext using RSA algorithm and any python library. At the time of writing this, I am using pyOpenSSL


Solution

  • I'd recommend using a more broad crypto library such as M2Crypto which has the X509 certificate functions as well as RSA encryption:

    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)