DEV Community

Dan Lumatic
Dan Lumatic

Posted on Originally published at demo.lumatic-labs.com AI-assisted

How to hash with SHA-256 in Python (and when not to)

hashlib.sha256("hello world") raises a TypeError. That's the first of three places where the famous one-line SHA-256 recipe needs one more line: strings need encoding, files need chunks, and passwords need a different function entirely.

TL;DR

  • hashlib.sha256(text.encode("utf-8")).hexdigest() gives 64 hex characters. Skip the .encode() and Python raises TypeError. Encode with a different charset and you get a different hash.
  • For files, call .update() on 1 MB chunks. On our 5 MB test file, peak memory was 2176 KiB instead of 5248 KiB, and the digest matched a whole-file read exactly.
  • For passwords, use stdlib hashlib.pbkdf2_hmac with a random salt per user, 200,000 iterations as a floor (our pick; raise it), and the iteration count stored inside the saved value. On our machine each guess was about 77,000 times slower than against plain SHA-256.

Hash a string in one line, after you encode it

Hashing works on bytes, so call .encode("utf-8") on your text and say which encoding you mean. The result is a 64-character hex string you can store, compare or use as a cache key.

hashlib ships with Python, so there is nothing to install. The hash object has .update(), .digest() and .hexdigest(), plus a few attributes (hashlib docs):

import hashlib

h = hashlib.sha256("hello world".encode("utf-8"))

print("hexdigest :", h.hexdigest())
print("len(hex)  :", len(h.hexdigest()))
print("digest_size:", h.digest_size)
print("name       :", h.name)
Enter fullscreen mode Exit fullscreen mode
hexdigest : b94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9
len(hex)  : 64
digest_size: 32
name       : sha256
Enter fullscreen mode Exit fullscreen mode

Why 64 characters? digest_size is 32 bytes, and each byte prints as two hex characters.

For a cache key built from several fields, serialize them as a JSON list before hashing. ("ab", "c") and ("a", "bc") then get different keys, and a | inside a field can't fake a boundary:

import hashlib
import json

user_id, url = "u42", "/pricing"
key = hashlib.sha256(json.dumps([user_id, url]).encode("utf-8")).hexdigest()
print(key)
Enter fullscreen mode Exit fullscreen mode
7fe9d9dd30512a285d10ca43ad39500e87379be2a8049c44655b893d78c78aa4
Enter fullscreen mode Exit fullscreen mode

Now the trap. Pass a str straight in and Python refuses. The fix is the .encode() call above, and the second half of this script shows why the encoding argument matters:

import hashlib

try:
    hashlib.sha256("hello world")
except TypeError as e:
    print(f"TypeError: {e}")

# Same text, different bytes, different hash.
word = "caf\u00e9"  # cafe with an accented e
a = hashlib.sha256(word.encode("utf-8")).hexdigest()
b = hashlib.sha256(word.encode("latin-1")).hexdigest()
print("utf-8   :", a)
print("latin-1 :", b)
print("equal?  :", a == b)
Enter fullscreen mode Exit fullscreen mode
TypeError: Strings must be encoded before hashing
utf-8   : 850f7dc43910ff890f8879c0ed26fe697c93a067ad93a7d50f466a7028a9bf4e
latin-1 : dafd66c0b98965e688be1fc12942c09f0350e6be0685017c3f234e97d0adc92e
equal?  : False
Enter fullscreen mode Exit fullscreen mode

The crash is the friendly outcome. The quieter failure is the last three lines: the accented word hashes to two different digests depending on the encoding. If one service hashes UTF-8 and another hashes Latin-1, their checksums will never match, and no error tells you why. Pick UTF-8, write it in the code, and keep it the same everywhere.

Hash a file in 1 MB chunks instead of reading it whole

Read the file one chunk at a time, call .update() on each chunk, and take the digest at the end; it is identical to hashing the whole file at once. hashlib.sha256(f.read()) works on a small file and loads a multi-gigabyte ISO entirely into RAM.

The script below builds a 5 MB file from a fixed seed and compares the chunked digest against a whole-read hash:

import hashlib
import os
import random
import tempfile

CHUNK = 1024 * 1024  # 1 MB


def sha256_file(path, chunk_size=CHUNK):
    h = hashlib.sha256()
    with open(path, "rb") as f:
        while chunk := f.read(chunk_size):
            h.update(chunk)
    return h.hexdigest()


rng = random.Random(1234)
block = bytes(rng.randrange(256) for _ in range(1024))
data = block * 5120  # 5 MB, same bytes every run

fd, path = tempfile.mkstemp()
try:
    with os.fdopen(fd, "wb") as f:
        f.write(data)
    chunked = sha256_file(path)
    with open(path, "rb") as f:
        whole = hashlib.sha256(f.read()).hexdigest()
    print("chunked :", chunked)
    print("whole   :", whole)
    print("equal?  :", chunked == whole)
except OSError as e:
    print("file error:", e)
finally:
    os.remove(path)
Enter fullscreen mode Exit fullscreen mode
chunked : ca503373c9056f5c283af799f392b6bbfe2ef41b1c1149d6f39ac1c6a3d85615
whole   : ca503373c9056f5c283af799f392b6bbfe2ef41b1c1149d6f39ac1c6a3d85615
equal?  : True
Enter fullscreen mode Exit fullscreen mode

On Python 3.11 and newer, hashlib.file_digest() does this loop for you. The chunk loop above also works on 3.8+, which matters if you still support older interpreters.

Matching digests say nothing about memory, so here is the peak measured with tracemalloc on the same 5 MB file (all timings and memory figures in this post come from one machine, so your numbers will differ a little):

import tracemalloc


def peak_kib(fn, path):
    tracemalloc.start()
    fn(path)
    peak = tracemalloc.get_traced_memory()[1]
    tracemalloc.stop()
    return peak // 1024


def whole_read(path):
    with open(path, "rb") as f:
        return hashlib.sha256(f.read()).hexdigest()


# path: the 5 MB file from above, or any file near that size
print("chunked peak   :", peak_kib(sha256_file, path), "KiB")
print("whole-read peak:", peak_kib(whole_read, path), "KiB")
Enter fullscreen mode Exit fullscreen mode
chunked peak   : 2176 KiB
whole-read peak: 5248 KiB
Enter fullscreen mode Exit fullscreen mode

Reading the whole file peaks at about the file size, 5248 KiB here. The chunked loop peaks at 2176 KiB, roughly two chunks' worth. With a 5 GB ISO, the whole-read version would ask for about 5 GB, while the loop would still hold only a couple of chunks.

The same function finds duplicate files. Group paths by digest, and any digest with two names is a duplicate pair. This script builds three small files in a temp folder, two with identical text, so you can run it as is:

import hashlib
import tempfile
from collections import defaultdict
from pathlib import Path


def sha256_file(path, chunk_size=1024 * 1024):  # same function as above
    h = hashlib.sha256()
    with open(path, "rb") as f:
        while chunk := f.read(chunk_size):
            h.update(chunk)
    return h.hexdigest()


with tempfile.TemporaryDirectory() as folder:
    docs = Path(folder)
    (docs / "report_v1.txt").write_text("Q3 numbers\n")
    (docs / "backup_report.txt").write_text("Q3 numbers\n")
    (docs / "summary.txt").write_text("Q3 summary\n")

    groups = defaultdict(list)
    for p in sorted(docs.iterdir()):
        if p.is_file():
            groups[sha256_file(p)].append(p.name)

for digest, names in groups.items():
    print(f"{digest[:16]}... -> {names}")
Enter fullscreen mode Exit fullscreen mode
4cfb5fc58b4acd4d... -> ['backup_report.txt', 'report_v1.txt']
b4ab539ed7fda9b9... -> ['summary.txt']
Enter fullscreen mode Exit fullscreen mode

The two files with the same text share a digest, so they hold identical bytes whatever they are called.

Try this: you just downloaded a release archive and the project's page lists a SHA-256 checksum. Copy sha256_file above, point it at the archive and compare the output to the published value. A mismatch means the file is corrupted or was altered, so don't install it.

Use SHA-256 for anything an attacker can touch

Use SHA-256 for anything an attacker could tamper with, and keep MD5 and SHA-1 for places where nobody can touch the input. The script prints all three digests of the same text and checks that SHA-256 is in the set every platform guarantees:

import hashlib

data = "hello world".encode("utf-8")
for name in ("md5", "sha1", "sha256"):
    h = hashlib.new(name, data)
    print(f"{name:7}{h.digest_size * 8:4} bits  {h.hexdigest()}")
print("sha256 guaranteed:", "sha256" in hashlib.algorithms_guaranteed)
Enter fullscreen mode Exit fullscreen mode
md5     128 bits  5eb63bbbe01eeed093cb22bb8f5acdc3
sha1    160 bits  2aae6c35c94fcfb415dbe95f408b9ce91ee846ed
sha256  256 bits  b94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9
sha256 guaranteed: True
Enter fullscreen mode Exit fullscreen mode

MD5 collisions were demonstrated long ago, and SHA-1 got a public collision in 2017. A collision means someone can craft two different files with the same hash, which defeats an integrity check. MD5 is acceptable only where nobody can tamper with the input, such as a local cache key, and even there SHA-256 costs you almost nothing extra. SHA-256 is specified in NIST FIPS 180-4, which is the document to cite if a compliance review asks.

When the algorithm name comes from a config file, hashlib.new(name, data) accepts it. Names in hashlib.algorithms_guaranteed exist on every platform, so stay inside that set if the code runs on someone else's machine.

Hash passwords with pbkdf2_hmac, a hash that is slow on purpose

Hash passwords with hashlib.pbkdf2_hmac, a fresh random salt per user, and the iteration count stored inside the saved value. Here is the version to paste. It returns one value holding the count, the salt and the hash, and check_password reads the count back out of it:

import hashlib
import hmac
import os

ITERATIONS = 200_000  # a floor; raise it, see the calibration loop below


def hash_password(password, iterations=ITERATIONS, salt=None):
    salt = salt if salt is not None else os.urandom(16)
    digest = hashlib.pbkdf2_hmac(
        "sha256", password.encode("utf-8"), salt, iterations
    )
    return iterations.to_bytes(4, "big") + salt + digest


def check_password(password, stored):
    iterations = int.from_bytes(stored[:4], "big")
    salt, digest = stored[4:20], stored[20:]
    candidate = hashlib.pbkdf2_hmac(
        "sha256", password.encode("utf-8"), salt, iterations
    )
    return hmac.compare_digest(candidate, digest)


stored = hash_password("correct horse battery staple")
print("stored bytes:", len(stored), "(4 count + 16 salt + 32 hash)")
print("iterations  :", int.from_bytes(stored[:4], "big"))
print("right password:", check_password("correct horse battery staple", stored))
print("wrong password:", check_password("wrong", stored))
Enter fullscreen mode Exit fullscreen mode
stored bytes: 52 (4 count + 16 salt + 32 hash)
iterations  : 200000
right password: True
wrong password: False
Enter fullscreen mode Exit fullscreen mode

Store that value in one column (or hex-encode it). The salt is not a secret. It exists because plain SHA-256 gives the same hash to every user who picks the same password, so one cracked guess would unlock all of them. In tests, pass salt= to get repeatable output.

Because each stored value carries its own count, raising ITERATIONS later only affects new hashes, and existing users keep verifying with the count they were saved with. Re-hash a user's password at login to move them up.

hmac.compare_digest compares in constant time. A plain == can stop at the first differing byte, and in a service that leaks a tiny timing signal.

Why all those iterations? SHA-256 is designed to be fast, which helps an attacker with a GPU test guesses in bulk against a stolen table of sha256(password) values. PBKDF2 repeats the hash hundreds of thousands of times, so each guess costs real CPU time. Here is what that costs, timed on the same machine as above:

import hashlib
import time


def avg_time(fn, runs):
    start = time.perf_counter()
    for _ in range(runs):
        fn()
    return (time.perf_counter() - start) / runs


fast = avg_time(lambda: hashlib.sha256(b"correct horse").digest(), 100_000) * 1e6
slow = avg_time(
    lambda: hashlib.pbkdf2_hmac("sha256", b"correct horse", b"salt" * 4, 200_000), 5
) * 1000
print(f"one sha256 call    : {fast:.1f} us")
print(f"pbkdf2, 200k rounds: {slow:.1f} ms")
print(f"slowdown           : {slow * 1000 / fast:,.0f}x")
Enter fullscreen mode Exit fullscreen mode
one sha256 call    : 0.3 us
pbkdf2, 200k rounds: 23.9 ms
slowdown           : 77,028x
Enter fullscreen mode Exit fullscreen mode

A login pays that 23.9 ms once. An attacker testing a million guesses pays it a million times: about 0.3 seconds of one core against plain SHA-256, and about 6.6 hours against PBKDF2 at 200,000 rounds, going by these timings.

So how many iterations? The 200,000 in the recipe is a floor we picked so a login stays cheap on modest hardware, and published guidance for PBKDF2 iteration counts has kept rising, so check the current figure before you ship. This loop finds your machine's number: it doubles the count from 100,000 until a single hash takes at least 100 ms (our example budget) and prints it. Our 23.9 ms at 200,000 rounds is well under that budget, so the loop prints a count well above the recipe's constant:

import hashlib
import time

iterations = 100_000
while True:
    start = time.perf_counter()
    hashlib.pbkdf2_hmac("sha256", b"benchmark", b"0" * 16, iterations)
    if time.perf_counter() - start >= 0.1:
        break
    iterations *= 2
print("use at least", iterations)
Enter fullscreen mode Exit fullscreen mode
use at least 1600000
Enter fullscreen mode Exit fullscreen mode

Read the two numbers together: 200,000 is the minimum we'd hard-code, and the printed count is what your hardware and your login budget actually allow. Set ITERATIONS to the printed value, or higher.

pbkdf2 is the stdlib answer, and hashlib.scrypt is a memory-hard option that is in the standard library too. If you can add a dependency, argon2 is the stronger default.

Quick answers

Is SHA-256 reversible?

No. It maps any input to a fixed 256 bits, and information is thrown away along the way, so there is nothing to decrypt. "Cracking" a hash means guessing inputs and hashing each one until the output matches. That is why guess speed matters so much for passwords.

Why does my hash change when I add a byte?

Any change to the input, even one byte or a trailing newline, produces a completely different digest. This is what makes checksums useful: if the hash matches, the bytes match. It is also why a hash computed over "hello world\n" won't equal one over "hello world".

Text means encode, files mean chunk, passwords mean pbkdf2

Encode text to UTF-8 explicitly, feed files through .update() one chunk at a time, and hash passwords with pbkdf2 and an iteration count saved inside the stored value. Re-run the calibration loop whenever you move to new hardware, and raise ITERATIONS if the printed number has gone up.

Try this: for a one-off checksum with no script, paste hello world into a browser-based hash generator and compare it with the digest from the first recipe, b94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9. A different result means an encoding or trailing-newline problem.

Top comments (0)