Python SHA-256 Hash Code Example (Online Runner)
Python SHA-256 hashing code example with runnable snippets to calculate SHA-256 and verify results online.
Online calculator: use the site SHA-256 text tool.
Calculation method
Use hashlib.sha256, encode text to bytes, and call hexdigest() for a 64-character hex digest.
Implementation notes
- Package: built-in
hashlib. - Implementation: SHA-256 works on bytes, so text encoding affects the result. File hashing uses chunked reads to avoid loading large files in memory.
- Notes: SHA-256 is not keyed; use HMAC for authenticated hashing or use a password hash (Argon2/scrypt) for passwords.
python
import hashlib
def sha256_text(text: str, encoding: str = "utf-8") -> str:
return hashlib.sha256(text.encode(encoding)).hexdigest()
# Example usage
from hashlib import sha256
payload = "hello world"
digest = sha256(payload.encode("utf-8")).hexdigest()
print(digest)
File hashing example
python
from pathlib import Path
import hashlib
import tempfile
def sha256_file(path: Path, chunk_size: int = 1024 * 1024) -> str:
hasher = hashlib.sha256()
with path.open("rb") as handle:
for chunk in iter(lambda: handle.read(chunk_size), b""):
hasher.update(chunk)
return hasher.hexdigest()
if __name__ == "__main__":
with tempfile.TemporaryDirectory() as temp_dir:
sample_path = Path(temp_dir) / "example.bin"
sample_path.write_bytes(b"example payload\n")
print(sha256_file(sample_path))If you create files with echo, note it appends a newline by default. Use echo -n or include a \n byte to match
this digest.
SHA-256 file hashes are computed from the file bytes only. The filename or path is not included unless you explicitly hash it as part of the input.
When to use SHA-256
SHA-256 is a general-purpose cryptographic hash used for integrity checks, signatures, and IDs. For passwords, use a dedicated password hash such as Argon2 or scrypt.
Test vectors
| Input | Expected SHA-256 |
|---|---|
| (empty string) | e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 |
abc | ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad |
message digest | f7846f55cf23e14eebeab5b4e1550cad5b509e3348fbc4efa3a1413d393cb650 |
abcdefghijklmnopqrstuvwxyz | 71c480df93d6ae2f1efad1447c66c9525e316218cf51fc8d9ed832f2daf18b73 |
Complete script (implementation + tests)
python
import hashlib
TEST_VECTORS = {
"": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
"abc": "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad",
"message digest": "f7846f55cf23e14eebeab5b4e1550cad5b509e3348fbc4efa3a1413d393cb650",
"abcdefghijklmnopqrstuvwxyz": "71c480df93d6ae2f1efad1447c66c9525e316218cf51fc8d9ed832f2daf18b73",
}
def sha256_hex(data: bytes) -> str:
return hashlib.sha256(data).hexdigest()
def sha256_text(text: str, encoding: str = "utf-8") -> str:
return sha256_hex(text.encode(encoding))
def run_tests() -> None:
for text, expected in TEST_VECTORS.items():
actual = sha256_text(text)
assert actual == expected, f"SHA-256 mismatch for {text!r}: {actual} != {expected}"
print("All SHA-256 test vectors passed.")
if __name__ == "__main__":
run_tests()