🚀 Supercharge your YouTube channel's growth with AI.
Try YTGrowAI FreeHow to Write an Encryption Program in Python?

I keep coming back to encryption whenever I need to secure API keys, store sensitive config, or send data between services. Python makes this surprisingly approachable, and in this guide I’ll walk through building an encryption program from scratch.
We’ll cover the basics of cryptography, why encryption matters in 2026, and three different approaches you can use today. By the end, you’ll have a working encryption tool and a clear picture of when to use each method.
TLDR
- Python’s
cryptographymodule is the standard for secure encryption - Fernet (symmetric encryption) works best for most practical applications
- Never roll your own crypto for production use
- Always store encryption keys separately from encrypted data
What is Cryptography?
Cryptography is the practice of converting readable data (plaintext) into an unreadable format (ciphertext) using mathematical algorithms and keys. Only someone with the correct key can reverse the process and read the original data.
The three goals of cryptography are confidentiality (nobody else can read your data), authenticity (you can verify who created the data), and integrity (you can detect if the data was tampered with).
What is Encryption and Decryption?
Encryption is the process of turning plaintext into ciphertext. You run your original data through an algorithm with a key, and you get back a scrambled result that looks like gibberish without the key.
Decryption is the reverse process. You run the ciphertext through the same algorithm with the same key (or a related key), and you get back your original plaintext.
How to Write an Encryption Program in Python
There are several ways to encrypt data in Python. I’ll show you three approaches, ranging from educational examples to production-ready code.
Approach 1: ASCII Shift Encryption
This approach shifts each character by a fixed number of positions in the ASCII table. It’s simple and works well for understanding the concept, but it’s not secure enough for real applications.
def encrypt_ascii(message, shift=3):
result = ""
for char in message:
result += chr(ord(char) + shift)
return result
def decrypt_ascii(ciphertext, shift=3):
result = ""
for char in ciphertext:
result += chr(ord(char) - shift)
return result
# Test it
original = "Hello!"
encrypted = encrypt_ascii(original)
decrypted = decrypt_ascii(encrypted)
print(f"Original: {original}")
print(f"Encrypted: {encrypted}")
print(f"Decrypted: {decrypted}")
The ord() function gets the Unicode code point of a character, and chr() converts it back. Adding a shift value scrambles the text. To decrypt, you subtract the same shift.
Approach 2: String Reversal with ASCII
This builds on the first approach by adding a reversal step. The idea is that scrambling the order makes the result harder to decode without knowing both the shift and the reversal.
def encrypt_reversal(message, shift=3):
# First encrypt with ASCII shift
encrypted = ""
for char in message:
encrypted += chr(ord(char) + shift)
# Then reverse the string
return encrypted[::-1]
def decrypt_reversal(ciphertext, shift=3):
# Reverse first
reversed_text = ciphertext[::-1]
# Then decrypt
result = ""
for char in reversed_text:
result += chr(ord(char) - shift)
return result
# Test it
original = "Secret Message"
encrypted = encrypt_reversal(original)
decrypted = decrypt_reversal(encrypted)
print(f"Original: {original}")
print(f"Encrypted: {encrypted}")
print(f"Decrypted: {decrypted}")
The slicing syntax [::-1] reverses a string in Python. This adds a layer of obfuscation, but I should be clear: both of these approaches are educational at best. Real encryption needs algorithms that have been tested against serious attacks.
Approach 3: Fernet (Production-Ready Encryption)
Fernet is a symmetric encryption system built into Python’s cryptography module. Symmetric means the same key encrypts and decrypts. Fernet also handles key generation, padding, and authentication automatically.
Install the module first:
pip install cryptography
Then use it in your code:
from cryptography.fernet import Fernet
# Generate a key (do this once and save it securely)
key = Fernet.generate_key()
print(f"Keep this key safe: {key.decode()}")
# Create a Fernet cipher instance
cipher = Fernet(key)
# Encrypt a message
message = b"This is sensitive data - keep it secret!"
encrypted = cipher.encrypt(message)
print(f"Encrypted: {encrypted}")
# Decrypt the message
decrypted = cipher.decrypt(encrypted)
print(f"Decrypted: {decrypted.decode()}")
The Fernet.generate_key() creates a URL-safe base64-encoded key. The encrypt() method returns bytes, and decrypt() reverses it. The ciphertext includes a timestamp, so old messages can be rejected if needed.
Storing Your Encryption Key Safely
Never hardcode encryption keys in your source code. Instead, store them in environment variables or a secrets manager. Here’s a pattern I use:
import os
from cryptography.fernet import Fernet
# Load key from environment variable
key = os.environ.get('ENCRYPTION_KEY')
if not key:
# Generate a new key if none exists (first run)
key = Fernet.generate_key()
print(f"Generated new key: {key.decode()}")
print("Set ENCRYPTION_KEY environment variable for next time")
cipher = Fernet(key)
FAQ
Q: Should I use the ASCII shift methods for real applications?
No. Those approaches are educational only. They use trivial transformations that are easy to break with basic cryptanalysis. Use Fernet or another well-vetted library for anything real.
Q: What’s the difference between symmetric and asymmetric encryption?
Symmetric encryption uses the same key to encrypt and decrypt. Asymmetric encryption uses a pair of keys (public and private). Fernet is symmetric, which is faster and simpler for most use cases where you control both ends of the communication.
Q: Can I encrypt files with these methods?
Yes. Fernet can handle any bytes, including file content. For large files, consider reading in chunks to avoid memory issues. For very large files, look into specialized tools like Python’s cryptography module with its AEAD ciphers for better performance.
Q: How do I share encrypted data with someone else?
You need to share the encryption key securely. Options include sharing it through a separate secure channel, using a key exchange protocol like Diffie-Hellman, or using asymmetric encryption to wrap the symmetric key before sending it.


