Search code examples
pythonencryptionopensslpublic-key-encryption

How to encrypt a string using python Openssl public key?


My current code to generate an OpenSSL public-private key pair:

import OpenSSL

key = OpenSSL.crypto.PKey()
key.generate_key(OpenSSL.crypto.TYPE_RSA, 2048)
public_key = OpenSSL.crypto.dump_publickey(OpenSSL.crypto.FILETYPE_PEM, key)
private_key = OpenSSL.crypto.dump_privatekey(OpenSSL.crypto.FILETYPE_PEM, key)
print(public_key, private_key, sep="\n")

Solution

  • The documentation recommends that you call key.to_cryptography_key() to get a cryptographic key, and then use pyca/cryptography to perform the encryption.

    https://www.pyopenssl.org/en/stable/api/crypto.html

    Given your crypto key:

    result = crypto_key.encrypt(b"Hello there")
    

    I should add, RSA is primary intended for signatures and verification, and key exchange. It's way too slow for general encryption.