Practical encryption and decryption in Python: a hands-on guide
Encryption can sound like a complex, mysterious topic reserved for security experts. But what if I told you that you can implement strong encryption and decryption with just a few lines of Python?
Let's dive into some practical examples to see how you can start protecting data in your own applications.
A tale of two cryptos: symmetric vs. asymmetric
Before we code, it's important to know the two main types of encryption:
Let's see them in action!
Example 1: Symmetric encryption with AES 🚀
We'll use Python's modern cryptography library. First, install it: pip install cryptography
Now, let's encrypt and decrypt a message using AES in GCM mode, which provides both confidentiality and integrity.
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
import os
# --- Encryption ---
data = b"This is a top-secret message."
key = AESGCM.generate_key(bit_length=128) # Generate a secret key
aesgcm = AESGCM(key)
nonce = os.urandom(12) # A "number used once" for security
encrypted_data = aesgcm.encrypt(nonce, data, None)
print(f"Encrypted: {encrypted_data.hex()}")
# --- Decryption ---
# You need the same key and nonce to decrypt
decrypted_data = aesgcm.decrypt(nonce, encrypted_data, None)
print(f"Decrypted: {decrypted_data.decode()}")
Key takeaway: To decrypt, you must have the exact same key and nonce. This is why securely managing and sharing the secret key is the biggest challenge of symmetric encryption.
Recommended by LinkedIn
Example 2: Asymmetric encryption with RSA ✉️
With RSA, you can give your public key to anyone. They can use it to encrypt a message that only you can decrypt with your private key.
from cryptography.hazmat.primitives.asymmetric import rsa, padding
from cryptography.hazmat.primitives import hashes
# First, generate a private/public key pair
private_key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
public_key = private_key.public_key()
# --- Encryption with the Public Key ---
message = b"You can only read this if you have the private key."
encrypted_message = public_key.encrypt(
message,
padding.OAEP(
mgf=padding.MGF1(algorithm=hashes.SHA256()),
algorithm=hashes.SHA256(),
label=None
)
)
print(f"\nEncrypted: {encrypted_message.hex()}")
# --- Decryption with the Private Key ---
decrypted_message = private_key.decrypt(
encrypted_message,
padding.OAEP(
mgf=padding.MGF1(algorithm=hashes.SHA256()),
algorithm=hashes.SHA256(),
label=None
)
)
print(f"Decrypted: {decrypted_message.decode()}")
Key takeaway: The public key locks the box, but only the corresponding private key can unlock it. This solves the key-sharing problem!
From code to a trusted system 🏛️
These examples are fantastic for learning, but a real-world secure system needs more. How do you know if a public key you received is legitimate and not from an attacker?
That's the role of a Public Key Infrastructure (PKI). In a PKI, public keys are embedded into digital certificates, which are signed by a trusted Certificate Authority (CA). This creates a verifiable chain of trust. When your browser connects to a secure site, it's not just using encryption—it's using a PKI to validate the site's certificate first.
Managing these certificates—ensuring they are valid, renewed on time, and deployed correctly—is a critical but often challenging task.
Need to build a system that relies on trusted digital identities? At PKINOW, we provide trusted digital certificates and powerful automation tools to simplify your PKI and certificate lifecycle management, so you can focus on building great applications.
#Python #Cryptography #Encryption #CyberSecurity #DevSecOps #PKI #PKINOW #AES #RSA
Thanks for posting this 🙌🏻