← Back to section · Tutorials & Labs
First Steps with Cryptography in Python: Hashing, HMAC, and AES-GCM
Three fundamentals with the standard library and the cryptography package — hashing with hashlib, message authentication with hmac, encryption with AES-GCM — plus the three beginner traps to avoid: ECB, home-grown randomness, and hashing-as-encryption.
First, Separate the Three Jobs
Beginners tend to stir cryptography into one pot. In practice there are only three everyday needs: integrity (the data was not modified) — use a hash; authenticity (it really came from the key holder) — use a message authentication code; confidentiality (nobody else can read it) — use encryption. Below we do each one in Python, using only the standard library and the mainstream cryptography package. The first principle of cryptographic engineering applies throughout: use audited libraries, never invent algorithms.
Step One: Hashing with hashlib
import hashlib
data = "post-quantum".encode("utf-8")
digest = hashlib.sha256(data).hexdigest()
print(digest)
# Output: c33472600b32ace662ab6b5e0b9496d61eb5f76e13a5f46dc60c144def587a0c
SHA-256 maps any input to a fixed digest of 64 hexadecimal characters (32 bytes). Two properties to remember: it is deterministic — the same input always yields the same output, which is exactly why it must not be used to store passwords (that needs a salted, slow password hash, a topic of its own) — and it has the avalanche effect: flip one input bit and the output is unrecognizable. File-integrity checks compare precisely this value.
Step Two: Message Authentication with hmac
A bare hash cannot stop forgery: an attacker who modifies the data can simply recompute the hash. Add a key known only to the communicating parties and the hash becomes an HMAC:
import hashlib
import hmac
key = b"demo-key" # in real code, a random key generated with secrets
msg = b"transfer:42"
tag = hmac.new(key, msg, hashlib.sha256).hexdigest()
print(tag)
# Output: 7f96fb233d57606792a1b9a6216e552afaa714c40f9869a33fa0ec320a20a9a1
# Always verify with compare_digest to avoid timing side channels
print(hmac.compare_digest(tag, hmac.new(key, msg, hashlib.sha256).hexdigest()))
# Output: True
Note hmac.compare_digest in the verification step: comparing strings with == returns early, byte by byte, and leaks timing information. Anything involving keys, tags, or tokens gets compared with compare_digest, without exception.
Step Three: AES-GCM Encryption with the cryptography Package
Install it first: pip install cryptography. The modern default for symmetric encryption is AES-GCM — it provides confidentiality and integrity together (authenticated encryption, AEAD), and the package’s high-level AESGCM interface wraps the details safely:
import secrets
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
key = AESGCM.generate_key(bit_length=256) # random key
aesgcm = AESGCM(key)
nonce = secrets.token_bytes(12) # 96-bit nonce, must be unique per encryption
plaintext = b"hello pqc"
ciphertext = aesgcm.encrypt(nonce, plaintext, None)
print(len(ciphertext)) # 25 = 9 bytes plaintext + 16-byte auth tag
print(aesgcm.decrypt(nonce, ciphertext, None))
# Output: b'hello pqc'
Two rules of discipline. First, never reuse a nonce under the same key — nonce reuse collapses GCM’s security; random 96-bit nonces plus a sane cap on encryptions per key is the low-effort safe pattern. Second, failed decryption raises an exception rather than returning garbage: if the tag does not verify, decrypt refuses outright. That refusal is precisely the value of authenticated encryption.
A Necessary Aside: Where Do Keys Come From?
The keys above are either fixed demo bytes or freshly generated by AESGCM.generate_key. In real systems, key management is where things break far more often than algorithm choice. Three basic rules. Never hard-code keys in source, and never commit them to a repository — inject them from environment variables or a dedicated key-management service. Use separate keys for separate purposes — one for encryption, another for authentication — rather than opening every lock with the same key. And plan for rotation and revocation from the start, so a leaked key can be replaced and retired. If a key must derive from a user password, it has to pass through a password-based key derivation function such as Argon2 or scrypt first; never use the password itself, or a single hash of it, directly as a key — passwords carry far too little entropy to withstand offline brute force.
Step Four: Deriving a Key from a Password — scrypt in Practice
Earlier we said a password must never be used directly as a key; here is the correct procedure, end to end. hashlib.scrypt, part of the standard library, is a password-based key derivation function that is deliberately slow and memory-hungry, pricing offline brute force out of reach.
import hashlib
import secrets
password = b"correct horse battery staple"
# At registration: generate a random salt, store it with the derived value
salt = secrets.token_bytes(16)
derived = hashlib.scrypt(password, salt=salt, n=2**14, r=8, p=1, dklen=32)
print(derived.hex())
# At login: recompute with the same parameters and compare
candidate = hashlib.scrypt(password, salt=salt, n=2**14, r=8, p=1, dklen=32)
print(secrets.compare_digest(derived, candidate)) # True
Three points. First, the salt must be random and per-user; store it alongside the derived value (the salt needs no secrecy). It makes identical passwords store as different values and renders precomputed rainbow tables useless. Second, the parameters n/r/p set the cost: n=2**14, r=8, p=1 is the classic RFC 7914 setting for interactive logins, using about 16 MB of memory. Store the parameters with the result so they can be raised smoothly as hardware improves. Third, compare with secrets.compare_digest, for the same reason as in the HMAC step — constant-time comparison leaves no timing side channel. New projects may prefer Argon2 (via the third-party argon2-cffi package), the password-hashing competition winner and the modern default; scrypt’s advantage is zero dependencies, straight from the standard library.
Note the contrast with Step One: SHA-256 is an integrity tool that should be as fast as possible; scrypt is a password tool that is slow on purpose. Storing passwords with the former or checksumming files with the latter is using both tools backwards.
Step Five: Streaming Hashes for Large Files
The Step One example read its input in one gulp. Real integrity checks run over files of several gigabytes, which demands chunked, streaming processing — and hashlib objects support it natively:
import hashlib
def file_sha256(path):
h = hashlib.sha256()
with open(path, "rb") as f:
while chunk := f.read(1024 * 1024): # read 1 MiB at a time
h.update(chunk)
return h.hexdigest()
print(file_sha256("disk-image.iso"))
update may be called any number of times; the result equals hashing the concatenation of all chunks, and the chunk size affects only memory and speed, never the digest. Compare the computed digest against the publisher’s value (again, prefer compare_digest), and you have the complete implementation of the “verify the SHA-256” step on every download page. Build the habit while you are here: anything important that arrives over a network — firmware, installers, datasets — gets its hash checked before use. When the publisher also ships a signature file, verify that too: the hash says “not corrupted”, the signature says “actually from them”; do not conflate the two jobs.
Three Beginner Traps
- ECB mode. ECB encrypts each block independently, so identical plaintext blocks produce identical ciphertext blocks — encrypt an image and its outline survives (the classic “ECB penguin”). Its only legitimate use today is as a cautionary tale.
- Home-grown randomness. Generating keys or nonces with the
randommodule, timestamps, or a formula of your own is a disaster.randomis designed for simulation and is predictable; cryptographic randomness comes fromsecrets(oros.urandom), full stop. - Hashing as encryption. A hash is one-way: there is no key and no decryption. “Encrypting” data by running SHA-256 over it is effectively publishing it — rainbow tables and dictionary attacks recover common content in moments. For confidentiality use AES-GCM; for storing passwords use a dedicated algorithm such as Argon2 or bcrypt.
Summary
Three fundamentals, three tools: hashlib for integrity, hmac for authenticity, AESGCM for confidentiality, and secrets for every random value. Internalize this combination and you gain a yardstick for everything that follows, asymmetric and post-quantum schemes included: for any proposal, ask which of the three jobs it does, and where its keys and randomness come from.
References
- Python standard library: hashlib — https://docs.python.org/3/library/hashlib.html
- Python standard library: hmac — https://docs.python.org/3/library/hmac.html
- Python standard library: secrets — https://docs.python.org/3/library/secrets.html
- cryptography package: AES-GCM — https://cryptography.io/en/latest/hazmat/primitives/aead/
Tags: PythonhashlibAES-GCMHMACcryptography