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

Mister PKI

SSL Certificates * SSL Tools * Certificate Decoder

  • Buy SSL Certificates
  • Blog
  • OpenSSL
  • Keytool
  • SSL Tools
  • Donate

Python Public Private Key Encryption

March 3, 2022 by Mister PKI Leave a Comment

SSL Certificates Leaderboard (728 x 90)

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

Training Courses

Top online courses in IT & Software

Cyber Security Training

Udemy - The Complete Internet Security Privacy Course icon

Buy SSL Certificates

The SSL Store

Comodo Store

Sectigo Store

RapidSSL

Recent Posts

  • pfx password
  • pkcs12
  • Sendmail vs Postfix – Mail Transfer Agent Comparison
  • Python mock datetime now
  • Python get SSL Certificate

Footer

  • Twitter
  • YouTube

Pages

  • About Mister PKI
  • Blog
  • Compare and Buy Affordable PKI Certificates
  • Contact Us
  • Full Disclosure
  • Privacy Policy
  • SSL Tools – Certificate Decoder and Certificate Checker

Copyright © 2022