• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
  • Skip to footer

Mister PKI

SSL Certificates * SSL Tools * Certificate Decoder

  • PKI Training
  • OpenSSL
  • Keytool
  • PKI Tools
    • Apereo CAS
    • SAML
    • OpenID Connect
  • Get expert help

Python Public Private Key Encryption

March 3, 2022 by Mister PKI Leave a Comment

The purpose of this article is to demonstrate how to use Python to perform public private key encryption. Public key encryption is a form of asymmetric encryption using a public and private key, different from symmetric encryption which uses a single shared secret key. For additional encryption examples please see previous posts we have written.

  • Encryption with Java
  • Encryption with OpenSSL
  • Encryption with JavaScript

In python, before encrypting with a public key you must first either have a key pair to read in from a file or generate one programmatically. Next, we will demonstrate how to generate a private key programmatically with python.

Python generate public private key pair

The code to generate a public private key pair in python is exactly the same as we have already demonstrated in our previous post on creating a CSR in python. We will again provide the code here for convenience.

This example will use the RSA algorithm for the key pair.

  1. Import the rsa library from the cryptography module
  2. Generate the RSA private key with public_exponent=65537 and key size 2048. Note that the key size of 2048 is the smallest recommended key size.
from cryptography.hazmat.primitives.asymmetric import rsa
# Generate the RSA private key
key = rsa.generate_private_key(
    public_exponent=65537,
    key_size=2048,
)

The RSA public private key pair is now stored in the key variable, ready to be used for encryption and decryption.

Encrypting data with a public key in Python

In case it is not yet clear, with RSA encryption the encryption is performed using the public key, not the private key. The private key will be used to decrypt the encrypted data.

RSA encryption with python is straightforward. One thing to be aware of is the different padding options.

  • OAEP – Recommended for new development.
  • PKCS1v15 – Should only be used to support legacy systems.
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.asymmetric import rsa, padding

message = b"secret text"
ciphertext = key.public_key().encrypt(
    message,
    padding.OAEP(
        mgf=padding.MGF1(algorithm=hashes.SHA256()),
        algorithm=hashes.SHA256(),
        label=None
    )
)

If you receive the following error, make sure you are trying to encrypt bytes and not a String. b"somestring" represent bytes instead of a String.

TypeError: initializer for ctype 'unsigned char *' must be a bytes or list or tuple, not str

Now you have encrypted text with you public key, ready to be decrypted with the private key in the next section.

Python RSA decrypt with private key

Now that you have encrypted data, the data can be decrypted with the matching RSA private key. To decrypt data in python with a private key, see the following code:

from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.asymmetric import rsa, padding
plaintext = key.decrypt(
    ciphertext,
    padding.OAEP(
        mgf=padding.MGF1(algorithm=hashes.SHA256()),
        algorithm=hashes.SHA256(),
        label=None
    )
)

Make sure to use the same padding and the matching private key to the public key used for encryption in the previous step.

print(plaintext == message)

The previous line should print True if the python RSA decryption was performed correctly.

If you receive the following error message you may have either used a non-matching public private key pair or used a different padding for the encryption and decryption steps.

ValueError: Encryption/decryption failed.

Conclusion

This article has demonstrated how to use Python public private key encryption. In addition, you should have learned how to decrypt using python and how to create a public private key pair with python. Leave us a comment with any questions on using python to perform encryption and decryption operations or if you would like to see additional examples.

python

Reader Interactions

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Primary Sidebar

Popular Posts

PKCS12

openssl s_client

Keytool

Keytool list

ECDSA vs RSA

OpenSSL

PKCS7

Certificate Decoder

PKI for DevOps Engineers – Free Training Series

PKI for DevOps Training Hub

Lesson 1 – How TLS and PKI Work

Lesson 2 – Understanding X.509 Certificates

Lesson 3 – Certificate Chains Explained

Lesson 4 – Debug TLS with OpenSSL

Lesson 5 – Verify Certificate Chains

Lesson 6 – Creating CSRs with OpenSSL

Lesson 7 – Working with PKCS12 Certificates

Lesson 8 – Java Keystores and keytool

Lesson 9 – Certificate Expiration Monitoring

Lesson 10 – Automating Certificate Renewal

Lesson 11 – Common TLS Errors

Lesson 12 – PKI Architecture for DevOps

Recent Posts

  • Apache mod_auth_cas: Protect Web Applications with Apereo CAS and Docker
  • Apache mod_auth_mellon: Configure SAML SSO & Docker
  • Configure OpenID Connect (OIDC) in Apereo CAS 7.3 and 8
  • Certificate Ownership Is an Operating Model Problem, Not a Tooling Problem
  • OpenSSL dgst: Create Checksums and Verify Digital Signatures

Footer

  • Twitter
  • YouTube
Mister PKI

Practical security engineering for the systems that establish trust.

Learn OpenSSL Keytool Free training
Work together PKI consulting CAS consulting Sponsored contributions
Site About Support Mister PKI Cookie policy Search
© 2026 Mister PKI Secure systems. Clear guidance.