UnixDroid

Lesson 10 of 12 · 7 min

Encrypt files with Python (Fernet and AES)

Hashing proves data hasn't changed; encryption keeps it secret and lets you get it back. Encrypt and decrypt a file in a few lines.

Hashing proves data hasn't changed; encryption keeps it secret and then lets you get it back. Every ethical hacker needs to understand it — to protect their own findings, and to recognise it in the wild. This lesson encrypts and decrypts a file in a few lines.

Hashing vs encryption

HashingEncryption
Reversible?NoYes, with the key
PurposeVerify integrityKeep data secret
ExamplePassword storageEncrypting a report

Confusing the two is a classic beginner mistake — a hash is a one-way fingerprint; encryption is a locked box you can reopen.

The easy, safe way: Fernet

The cryptography library's Fernet gives you strong AES encryption without the footguns.

from cryptography.fernet import Fernet

key = Fernet.generate_key()   # keep this secret!
f = Fernet(key)

secret = f.encrypt(b'engagement notes: port 22 open')
print(secret)

back = f.decrypt(secret)
print(back.decode())

Lose the key and the data is gone for good — which is the whole point of encryption done right.

Encrypting an actual file

with open('report.txt', 'rb') as file:
    data = file.read()

encrypted = f.encrypt(data)

with open('report.enc', 'wb') as file:
    file.write(encrypted)

Decrypting is the same in reverse with f.decrypt.

Tip: Never write your own crypto algorithm — use vetted libraries like cryptography. The hard part is never the maths; it's key management: where you store the key, who can read it, how you rotate it. Most real-world breaks are stolen keys, not broken ciphers.

Why attackers care too

Ransomware is just file encryption pointed at a victim with the key withheld. Understanding how encryption works — and how fast a few lines can lock a folder — is exactly why defenders keep offline backups.

Try it yourself
  1. Generate a Fernet key and encrypt the string 'hello'.
  2. Decrypt it back and confirm you get 'hello' again.
  3. Encrypt a small text file into a .enc file, then decrypt it to a new file.
No Linux machine? Practise in the free online terminal

Quick check

Encryption can be undone, unlike hashing - but only if you have the what?

Need a hint?

It locks and unlocks the box.

Finished this lesson?

Done lessons keep your daily streak going 🔥

0 day streak

0 lessons done

best 0 days

Log in to keep your streak on every device →