On this page
  1. hashlib
  2. Import
  3. Overview
  4. Quick Start
  5. Implementation Walkthrough
  6. 1. Streaming File Checksums with file_digest() (Python 3.11+)
  7. 2. Password Hashing with scrypt + Random Salt
  8. Gotchas & Boundaries
  9. Common Functions
  10. Classes & Objects
  11. Constants & Attributes

hashlib

Prev: gzip | Up: stdlib_module | Next: heapq
Rel: hmac, secrets
Ref: docs.python.org — hashlib
Tags: #public #python3 #stdlib


Import

import hashlib

Overview

Cryptographic digest algorithms (sha256, sha512, blake2b, sha3_256) and password key derivation (scrypt, pbkdf2_hmac). Use hashlib.file_digest() (Python 3.11+) for streaming file checksums, hmac.compare_digest() for constant-time comparisons, and secrets for generating random tokens or salts.

Quick Start

import hashlib

digest = hashlib.sha256(b"hello world").hexdigest()
assert digest == "b94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9"

Implementation Walkthrough

1. Streaming File Checksums with file_digest() (Python 3.11+)

Avoid loading multi-gigabyte files into RAM; file_digest() reads in buffered chunks directly in C:

import hashlib
from pathlib import Path

def sha256_file(path: Path) -> str:
    with path.open("rb") as fh:
        return hashlib.file_digest(fh, "sha256").hexdigest()

2. Password Hashing with scrypt + Random Salt

Never hash passwords with plain sha256—use a slow, salted key derivation function (scrypt or pbkdf2_hmac) and constant-time verification:

import hashlib
import hmac
import secrets

salt = secrets.token_bytes(16)
key = hashlib.scrypt(b"correct-horse-battery", salt=salt, n=2**14, r=8, p=1)

# Verify candidate password:
candidate = hashlib.scrypt(b"correct-horse-battery", salt=salt, n=2**14, r=8, p=1)
assert hmac.compare_digest(key, candidate)

Gotchas & Boundaries

Common Functions

Classes & Objects

Constants & Attributes

Linked from

Related notes