Python cryptography example
Python cryptography example
Here's an example of how you can use the Fernet symmetric encryption algorithm in Python with the cryptography library:
from cryptography.fernet import Fernet
import base64
import os
import sys
def generate_key():
key = Fernet.generate_key()
return key
def encrypt_message(key, message):
cipher_suite = Fernet(key)
cipher_text = cipher_suite.encrypt(message.encode())
return cipher_text.decode()
def decrypt_message(key, cipher_text):
cipher_suite = Fernet(key)
plain_text = cipher_suite.decrypt(cipher_text.encode())
return plain_text.decode()
if name == "main":
Generate a keykey = generate_key()
print(f"Generated Key: {base64.b64encode(key).decode()}")
Get the message to encryptmessage = input("Enter your secret message: ")
if not message:
sys.exit(1)
Encrypt the messagecipher_text = encrypt_message(key, message)
print(f"Cipher Text: {cipher_text}")
Decrypt the messageplain_text = decrypt_message(key, cipher_text)
print(f"Plain Text: {plain_text}")
In this example:
We generate a key usingFernet.generate_key()
We encrypt a message using encrypt_message()
function We decrypt the encrypted message using decrypt_message()
function
The Fernet algorithm uses AES-128 in CBC mode with a 32-byte random initialization vector, and HMAC with SHA256 for authentication.
Here's how to run this script:
Save this code into a file namedfernet.py
Run the script by executing `python fernePython cryptography AES
I'm happy to provide a detailed explanation of the Python cryptography library and its usage with AES encryption.
Python's cryptography library is an amazing tool that allows you to work with cryptographic primitives like symmetric encryption (AES, Blowfish), asymmetric encryption (RSA, Elliptic Curve), digital signatures, and more. It provides a simple way to integrate cryptography into your projects.
Let's dive deeper into the basics of AES encryption using Python.
What is AES?
AES (Advanced Encryption Standard) is a widely used symmetric encryption algorithm that converts plaintext data into unreadable ciphertext. AES uses a 128-bit key size, which means it has a large key space to generate random keys.
How does AES work?
Key generation: AES requires a unique key for encryption and decryption. You can either generate a random key using a library likesecrets
in Python or use a password-based key derivation function (PBKDF) to create a derived key from a user-supplied password. Plaintext data: You have some plaintext data you want to encrypt, such as a file or message. Encryption: AES takes the plaintext and applies the encryption algorithm using the generated key. The process involves: Block cipher mode: Divide the plaintext into fixed-size blocks (typically 16 bytes). Each block is encrypted separately. Substitution: Replace each byte in the block with another byte, based on the key. Permutation: Rearrange the bytes to create a ciphertext block. Ciphertext output: The encrypted plaintext becomes the ciphertext.
Python Implementation
Here's an example of using AES encryption in Python:
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.backends import default_backend
Generate a random 16-byte key (128-bit)key = secrets.token_bytes(16)
Create an AES-256-CBC cipher objectcipher = Cipher(algorithms.AES(key), modes.CBC(b'00' * 16), backend=default_backend())
Encrypt some plaintext dataplaintext_data = b"Hello, World!"
ciphertext = cipher.encryptor().update(plaintext_data) + cipher.encryptor().finalize()
print(f"Ciphertext: {ciphertext.hex()}")
This example generates a random AES key, creates an AES-256-CBC cipher object, and encrypts the plaintext string "Hello, World!". The output is a ciphertext hexadecimal representation.
Key considerations
Key size: AES supports various key sizes (128-bit, 192-bit, or 256-bit). In this example, we used a 256-bit key. Initialization vector (IV): In CBC mode, you need to use an IV. This is usually generated randomly and sent along with the ciphertext. Encryption speed: AES encryption can be relatively slow compared to other algorithms like Blowfish or FISH.Conclusion
Python's cryptography library provides a robust way to work with cryptographic primitives like AES encryption. By understanding how AES works and implementing it using Python, you can create secure data protection solutions for your projects. Keep in mind the importance of key size, initialization vector (IV), and encryption speed when working with AES.
Feel free to ask if you have any questions or would like more details on other cryptographic primitives!