all Python 3hashlibfunction
hashlib.sha256()
hashing
Creates a SHA-256 hash object. A cryptographically strong algorithm. Use it for data integrity checks and digital signatures.
Syntax
hashlib.sha256(data=b'')
Being collision-resistant does not make SHA-256 suitable for passwords: it is fast, so a dictionary attack runs millions of hashes per second — use hashlib.pbkdf2_hmac() or hashlib.scrypt(), which are deliberately slow and salted. When comparing secret digests, use hmac.compare_digest() rather than ==, since a plain comparison bails out at the first differing byte and leaks timing information.
Examples
import hashlib
h = hashlib.sha256(b'secret data')
print(len(h.hexdigest())) # → 64 — шестнадцатеричных символов
import hashlib
# постепенная загрузка большого файла: память не зависит от его размера
with open('bigfile.bin', 'wb') as f:
f.write(b'x' * 200_000)
h = hashlib.sha256()
with open('bigfile.bin', 'rb') as f:
for chunk in iter(lambda: f.read(65536), b''):
h.update(chunk)
print(h.hexdigest() == hashlib.sha256(b'x' * 200_000).hexdigest()) # → True
See also
Common errors
Open in the full glossarydocs.python.orgReport an inaccuracy