hashlib.sha256, hash.update, hash.hexdigest, hash.copy
hashlib.sha256(data=b'', *, usedforsecurity=True)
hash.update(data)
hash.hexdigest()
hash.digest()
hash.copy()Hash bytes with SHA-256, including chunked update and a cloned state. Strings must be encoded first.
| Parameter | Description |
|---|---|
data | Bytes to hash. A str is not accepted; encode it explicitly, for example text.encode("utf-8"). |
usedforsecurity | Keyword-only. Leave the default True for algorithms that are still appropriate as cryptographic hashes. Official documentation uses False to allow a blocked or insecure algorithm for a non-security checksum. |
Returns: The constructor returns a hash object. hexdigest returns a str of hexadecimal digits. digest returns bytes. copy returns a new hash object with the same state.
Raises
TypeError— Raised when a str is passed where bytes are required. The measured message on Python 3.13.12 is "Strings must be encoded before hashing".
- The TypeError message was measured on Python 3.13.12.
import hashlib
digest = hashlib.sha256(b"abc")
print(digest.hexdigest())
chunked = hashlib.sha256()
chunked.update(b"ab")
chunked.update(b"c")
print(chunked.hexdigest() == digest.hexdigest())
clone = hashlib.sha256(b"ab")
copied = clone.copy()
clone.update(b"c")
print(copied.hexdigest() == hashlib.sha256(b"ab").hexdigest())
try:
hashlib.sha256("abc")
except TypeError as err:
print(type(err).__name__, err)Expected output
ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad
True
True
TypeError Strings must be encoded before hashing