Sitemap

Cryptography in Python — A practical example to code

3 min readJan 8, 2023

--

Press enter or click to view image in full size

Cryptography can be a bit intimidating at first, but once you have it down, you can use cryptography in Python to help keep your data private! In this tutorial we will explain how you can generate public and private keys with Python, as well as test whether the encryption and decryption worked. We will have a look at the RSA and the Elliptic Curve algorithm.

Get Tech Talk With Alex’s stories in your inbox

Join Medium for free to get updates from this writer.

The cryptography.hazmat.primitives.asymmetric library allows you to perform cryptographic tasks. You can use this library to construct, sign, verify and verify integrity of messages and files.

#Make sure you have Python 3.6 since pycparser only works with that version. You can use this code to verify your Python version. 
import sys
print(sys.version)

Creating RSA Key Pairs

The public_exponent is used to encrypt messages, and in RSA commonly used numbers are 3, 17, or 65537 — and note these are prime numbers, that are co-prime to the multiplied prime numbers making up your private key. The larger the numbers the more time it takes to encrypt/decrypt a message.

import base64
from cryptography.hazmat.primitives.asymmetric import rsa, padding
from cryptography.hazmat.primitives import serialization, hashes
# Generate a new RSA key pair
private_key = rsa.generate_private_key(
public_exponent=65537,
key_size=2048
)
public_key = private_key.public_key()
# Serialize the private key and the public key
private_key_pem = private_key.private_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PrivateFormat.PKCS8,
encryption_

Creating Elliptic Curve Key Pairs

In this example, we will use the elliptic curve algorithm to create a public/private key pair for encryption and decryption. We will then use the public key to encrypt a message and then decrypt it with the private key.

#Install the cryptography libraries

!pip install cryptography

from cryptography.hazmat.primitives.asymmetric import ec

# Generate a new elliptic curve key pair
private_key = ec.generate_private_key(ec.SECP256K1(), default_backend())
public_key = private_key.public_key()

# Print the public and private keys
print(f'Private key: {private_key}')
print(f'Public key: {public_key}')

Encrypting and Decrypting Elliptic Curve Key Pairs

Read this article if you want to get familiar with how encryption works in very detail on a mathematic level: https://medium.com/@TechTalkWithAlex/rsa-encryption-22963239a8ff

#Encryption
ciphertext = (message ^ public_exponent) mod (p * q)

#Decryption
message = (ciphertext ^ private_exponent) mod (p * q)

Here’s the environment that I’ll use to demonstrate how cryptography works:

from cryptography.hazmat.primitives.asymmetric import ec
from cryptography.hazmat.primitives.asymmetric import padding

# Load the public/private key pairs generated above
public_key = ...
private_key = ...

# Encrypt the message using the public key
message = b'The secret message no one should read'
ciphertext = public_key.encrypt(
message,
padding.OAEP(
mgf=padding.MGF1(algorithm=hashes.SHA256()),
algorithm=hashes.SHA256(),
label=None
)
)

# Decrypting the message (=cyphertext) using your private key
decrypted_message = private_key.decrypt(
ciphertext,
padding.OAEP(
mgf=padding.MGF1(algorithm=hashes.SHA256()),
algorithm=hashes.SHA256(),
label=None
)
)

# Printing the original and decrypted secret message
print(f'Original message: {message}')
print(f'Decrypted message: {decrypted_message}')

Disclaimer: The author of this article assumes no responsibility or liability for any errors or omissions in the content of this site. The information contained in this site is with no guarantees of completeness, accuracy, usefulness or timeliness.

--

--

Tech Talk With Alex
Tech Talk With Alex

Written by Tech Talk With Alex

At the end of the day, nothing is too hard to understand when it is explained simply. Making complex concepts easy for everyone to get smart!