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
| Hashing | Encryption | |
|---|---|---|
| Reversible? | No | Yes, with the key |
| Purpose | Verify integrity | Keep data secret |
| Example | Password storage | Encrypting 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.