Cryptography in Python: 3 Practical Examples

Explore three practical examples of implementing cryptography in Python, perfect for your next science fair project.
By Taylor

Understanding Cryptography in Python

Cryptography is a vital aspect of securing information, and Python provides an easy-to-use platform for implementing cryptographic techniques. Whether you’re interested in securing your data or learning more about how encryption works, these examples will help you understand the basics of cryptography in Python. Let’s dive into three practical examples that you can use for your science fair project!

Example 1: Simple Message Encryption with Fernet

Use Case

Imagine you want to send a secret message to a friend without anyone else being able to read it. Using the cryptography library in Python, you can easily encrypt and decrypt messages with a symmetric key. This means both you and your friend will use the same key to unlock the message.

Example

First, make sure to install the cryptography library if you haven’t already:

pip install cryptography

Next, you can use the following code to encrypt and decrypt a message:

from cryptography.fernet import Fernet

# Generate a key
key = Fernet.generate_key()
fernet = Fernet(key)

# Original message
message = b"This is a secret message."

# Encrypt the message
encrypted_message = fernet.encrypt(message)
print(f"Encrypted: {encrypted_message}")

# Decrypt the message
decrypted_message = fernet.decrypt(encrypted_message)
print(f"Decrypted: {decrypted_message.decode()}")

Notes

  • You can store the generated key securely and share it with your friend.
  • If you want to encrypt files instead of messages, you can read the file as bytes and apply the same encryption method.

Example 2: Secure Password Hashing

Use Case

When creating a website where users can log in, it’s essential to store their passwords securely. Instead of saving passwords in plain text, you can hash them using Python. Hashing transforms the password into a fixed-size string of characters that cannot be reversed.

Example

You can use the bcrypt library for hashing passwords. First, install it:

pip install bcrypt

Now, you can hash and check a password as follows:

import bcrypt

# Hash a password
password = b"my_secure_password"
hash = bcrypt.hashpw(password, bcrypt.gensalt())
print(f"Hashed Password: {hash}")

# Check if the provided password matches the hash
if bcrypt.checkpw(password, hash):
    print("Password matches!")
else:
    print("Password does not match!")

Notes

  • Ensure you use a strong password when hashing.
  • You can also implement password reset functionalities by re-hashing the new password.

Example 3: Creating a Digital Signature

Use Case

Digital signatures are used to verify the authenticity of a message or document. If you want to ensure that a document hasn’t been altered and is indeed from the claimed sender, you can use a digital signature.

Example

You can use the cryptography library to create a digital signature:

from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.asymmetric import rsa, padding

# Generate a private key
private_key = rsa.generate_private_key(
    public_exponent=65537,
    key_size=2048,
    backend=default_backend()
)

# Generate a public key
public_key = private_key.public_key()

# Original message
message = b"This is a document."

# Sign the message
signature = private_key.sign(
    message,
    padding.PSS(
        mgf=padding.MGF1(hashes.SHA256()),
        salt_length=padding.PSS.MAX_LENGTH
    ),
    hashes.SHA256()
)
print(f"Signature: {signature}")

# Verify the signature
try:
    public_key.verify(
        signature,
        message,
        padding.PSS(
            mgf=padding.MGF1(hashes.SHA256()),
            salt_length=padding.PSS.MAX_LENGTH
        ),
        hashes.SHA256()
    )
    print("Signature is valid.")
except Exception as e:
    print("Signature is invalid:", e)

Notes

  • Digital signatures are crucial in email communication and software distribution.
  • Make sure to protect your private key, as it is used to create the signature.

These examples of implementing cryptography in Python not only demonstrate how to secure your data but also provide a great foundation for understanding more complex cryptographic concepts. Good luck with your science fair project!