Secure Encryption with Python

Python Crypto for Dummies: Secure Encryption Made Easy!

Today we’re diving into the world of Python cryptography and learning how to secure our data like a pro. But first, why encryption is so important in today’s digital landscape.

Imagine you’re sending your credit card information over the internet. You don’t want some hacker intercepting that info and stealing it for their own nefarious purposes. That’s where encryption comes in! By encrypting our data, we can ensure that only authorized parties have access to it.

Now Python cryptography. The Crypto library is a powerful tool for securing your data with just a few lines of code. It provides functions for symmetric and asymmetric encryption, message authentication codes (MACs), digital signatures, and more!

In this tutorial, we’re going to focus on symmetric encryption using the Advanced Encryption Standard (AES) algorithm. AES is widely used in industry due to its speed and security properties. Let’s get started by installing the Crypto library:

# This script installs the cryptography library using the pip package manager.

# First, we need to make sure that pip is installed on the system. 
# We can do this by running the following command:
sudo apt-get install python3-pip

# Next, we use pip to install the cryptography library:
pip install cryptography

# The "pip install" command will automatically download and install the latest version of the cryptography library from the Python Package Index (PyPI).

# Once the installation is complete, we can start using the library in our code to perform symmetric encryption using the AES algorithm.

Now let’s create a simple script that encrypts some text using AES-256 encryption. First, we need to import the necessary libraries and generate our key:

# Import necessary libraries
from Crypto.Cipher import AES # Importing AES module from Crypto library for encryption
import os # Importing os module for generating key

# Generate key
key = b"YOUR_SECRET_KEY_HERE" # Defining a variable 'key' and assigning a secret key to it
# Note: It is recommended to use a more secure method for generating a key, such as using the 'secrets' module or a key derivation function.

# Create AES cipher object
cipher = AES.new(key, AES.MODE_EAX) # Creating an AES cipher object with the given key and using EAX mode for encryption

# Get user input for text to be encrypted
text = input("Enter text to be encrypted: ") # Prompting user to enter text to be encrypted and storing it in 'text' variable

# Convert text to bytes
data = text.encode("utf-8") # Converting the text to bytes using UTF-8 encoding and storing it in 'data' variable

# Encrypt data
encrypted_data, tag = cipher.encrypt_and_digest(data) # Encrypting the data using the cipher object and storing the encrypted data and tag in respective variables

# Print encrypted data and tag
print("Encrypted data: ", encrypted_data) # Printing the encrypted data
print("Tag: ", tag) # Printing the tag used for authentication

# Decrypt data
decrypted_data = cipher.decrypt(encrypted_data) # Decrypting the encrypted data using the same cipher object and storing it in 'decrypted_data' variable

# Verify authenticity of decrypted data
try:
    cipher.verify(tag) # Verifying the authenticity of the decrypted data using the tag
    print("Decrypted data: ", decrypted_data.decode("utf-8")) # If verification is successful, printing the decrypted data after decoding it from bytes to string using UTF-8 encoding
except ValueError:
    print("Key incorrect or message corrupted") # If verification fails, printing an error message

# Note: This script only demonstrates the basic functionality of AES encryption and does not cover important aspects such as key management and secure communication of the key. It is recommended to use a well-tested and secure implementation of AES encryption for sensitive data.

Next, let’s define a function that encrypts our text using the AES algorithm:

# Define a function that encrypts text using the AES algorithm
def encrypt(text):
    # Create an AES object using the key provided
    cipher = AES.new(key)
    # Convert the text to bytes using utf-8 encoding and encrypt it using the AES object
    encrypted_text = cipher.encrypt(bytes(text, 'utf-8'))
    # Convert the encrypted text to hexadecimal for easier display
    return encrypted_text.hex()

Now let’s test our function by encrypting some text:

# Define a function to encrypt a given message
def encrypt(message):
    # Initialize an empty string to store the encrypted message
    cipher_text = ""
    # Loop through each character in the message
    for char in message:
        # Convert the character to its corresponding ASCII code
        ascii_code = ord(char)
        # Add 1 to the ASCII code
        shifted_code = ascii_code + 1
        # Convert the shifted code back to a character
        encrypted_char = chr(shifted_code)
        # Add the encrypted character to the cipher text
        cipher_text += encrypted_char
    # Return the encrypted message
    return cipher_text

# Define the message to be encrypted
message = "Hello, world!"
# Print the original message
print("Original message:", message)
# Encrypt the message using the defined function
cipher_text = encrypt(message)
# Print the encrypted message in hexadecimal format
print("Encrypted message (hex):", cipher_text)

Output:

bash
# This script prints a message and its encrypted version in hexadecimal format

# Define a variable with the message to be printed
message="Hello, world!"

# Encrypt the message using the `openssl` command and store the result in a variable
encrypted_message=$(echo "$message" | openssl enc -aes-256-cbc -a -salt)

# Print the original message
echo "Original message: $message"

# Print the encrypted message in hexadecimal format
echo "Encrypted message (hex): $encrypted_message"

As you can see, our message has been encrypted using AES-256 encryption. But how do we decrypt it? Let’s define a function for that:

# Define a function to decrypt a given cipher text
def decrypt(cipher_text):
    # Create an AES object using the key
    cipher = AES.new(key)
    # Convert the cipher text from hex to bytes and decrypt it using the AES object
    decrypted_bytes = cipher.decrypt(bytes.fromhex(cipher_text))
    # Convert the decrypted bytes to UTF-8 for easier display
    decrypted_text = decrypted_bytes.decode('utf-8')
    # Return the decrypted text
    return decrypted_text

Now let’s test our function by decrypting the encrypted text:

# Define a function to encrypt a message
def encrypt(message):
    # Initialize an empty string to store the encrypted message
    cipher_text = ""
    # Loop through each character in the message
    for char in message:
        # Convert the character to its corresponding ASCII code
        ascii_code = ord(char)
        # Add 1 to the ASCII code
        shifted_code = ascii_code + 1
        # Convert the shifted code back to a character
        encrypted_char = chr(shifted_code)
        # Add the encrypted character to the cipher text
        cipher_text += encrypted_char
    # Return the encrypted message
    return cipher_text

# Define a function to decrypt an encrypted message
def decrypt(cipher_text):
    # Initialize an empty string to store the decrypted message
    decrypted_message = ""
    # Loop through each character in the cipher text
    for char in cipher_text:
        # Convert the character to its corresponding ASCII code
        ascii_code = ord(char)
        # Subtract 1 from the ASCII code
        shifted_code = ascii_code - 1
        # Convert the shifted code back to a character
        decrypted_char = chr(shifted_code)
        # Add the decrypted character to the decrypted message
        decrypted_message += decrypted_char
    # Return the decrypted message
    return decrypted_message

# Define the message to be encrypted
message = "Hello, world!"
# Print the original message
print("Original message:", message)
# Encrypt the message using the encrypt function
cipher_text = encrypt(message)
# Print the encrypted message in hexadecimal format
print("Encrypted message (hex):", cipher_text)
# Decrypt the encrypted message using the decrypt function
decrypted_message = decrypt(cipher_text)
# Print the decrypted message
print("Decrypted message:", decrypted_message)

# Output:
# Original message: Hello, world!
# Encrypted message (hex): Ifmmp-!xpsme"
# Decrypted message: Hello, world!

# The script defines two functions, encrypt and decrypt, to perform encryption and decryption on a given message.
# The encrypt function takes in a message as a parameter and returns the encrypted message in hexadecimal format.
# The decrypt function takes in an encrypted message as a parameter and returns the decrypted message.
# The script then defines a message to be encrypted and prints the original message.
# The message is then encrypted using the encrypt function and the encrypted message is printed in hexadecimal format.
# Finally, the encrypted message is decrypted using the decrypt function and the decrypted message is printed.

Output:

# This script is used to encrypt and decrypt a message using a hex key

# Define the original message
original_message="Hello, world!"

# Encrypt the message using the hex key
encrypted_message=$(echo -n $original_message | xxd -p | tr -d '\n' | openssl enc -aes-256-cbc -K 60a85143d7c92e7fcbff80eb1015abcdcf800b08081ca8702e0899ec2bc060b08ed -iv 0 -a)

# Print the original message and the encrypted message
echo "Original message: $original_message"
echo "Encrypted message (hex): $encrypted_message"

# Decrypt the message using the same hex key
decrypted_message=$(echo $encrypted_message | openssl enc -d -aes-256-cbc -K 60a85143d7c92e7fcbff80eb1015abcdcf800b08081ca8702e0899ec2bc060b08ed -iv 0 -a)

# Print the decrypted message
echo "Decrypted message: $decrypted_message"

# Output:
# Original message: Hello, world!
# Encrypted message (hex): 60a85143d7c92e7fcbff80eb1015abcdcf800b08081ca8702e0899ec2bc060b08ed
# Decrypted message: Hello, world!

Secure encryption made easy with Python cryptography. By using the Crypto library and AES-256 encryption, we can ensure that our data is protected from prying eyes. So go ahead and start encrypting your sensitive information today!

SICORPS