Skip to main content

SHA-256 Hashing in Python: hashlib Complete Guide

Hash strings and files with SHA-256 in Python using the built-in hashlib module. Includes HMAC examples and a free online SHA-256 generator to verify output.

Python's standard library includes the hashlib module, which provides access to SHA-256 and all other SHA-2 hashing algorithms. No pip install is required — hashlib ships with every Python installation. This makes SHA-256 hashing in Python as simple as a three-line function, and the same approach works across Python 3.x versions.

How to Use the SHA-256 Generator Tool

  1. Enter your text — Paste the string you want to hash into the input field.
  2. Generate the hash — The tool returns a 64-character hexadecimal SHA-256 digest.
  3. Copy and use the result — Compare it with your Python output to confirm your implementation is correct.
  4. Use the code examples below — Drop the function into your Python script and start hashing.

Basic SHA-256 with hashlib

import hashlib

def sha256(text: str) -> str:
    return hashlib.sha256(text.encode('utf-8')).hexdigest()

# Usage
print(sha256('hello world'))
# b94d27b9934d3e08a52e52d7da7dabfac484efe04294e576b94...

Hashing a File with SHA-256 in Python

import hashlib

def sha256_file(filepath: str) -> str:
    h = hashlib.sha256()
    with open(filepath, 'rb') as f:
        # Read in chunks to handle large files
        for chunk in iter(lambda: f.read(8192), b''):
            h.update(chunk)
    return h.hexdigest()

print(sha256_file('/path/to/file.zip'))

Why Use SHA-256 in Python?

  • Built-in, no dependencieshashlib is part of Python's standard library. Nothing to install.
  • Fast native implementation — Python's hashlib calls OpenSSL under the hood, making it very fast for large inputs.
  • File integrity verification — Reading large files in chunks and updating the hash incrementally prevents memory issues.
  • Consistent across platforms — The same Python code produces the same SHA-256 hash on Windows, macOS, and Linux.

SHA-256 for HMAC Authentication in Python

A common use of SHA-256 is in HMAC (Hash-based Message Authentication Code) for API authentication. Python's hmac module works alongside hashlib for this:

import hmac
import hashlib

def generate_hmac(secret: str, message: str) -> str:
    key = secret.encode('utf-8')
    msg = message.encode('utf-8')
    return hmac.new(key, msg, hashlib.sha256).hexdigest()

Encoding Notes

Always call .encode('utf-8') before hashing a Python string. The SHA-256 function operates on bytes, not strings. If you pass a string directly, you will get a TypeError. For binary data (e.g., image bytes), pass the raw bytes object directly without encoding.

Verify your Python SHA-256 output matches expected values using the SHA-256 Generator online.