all Python 3hashlibfunction
hashlib.new()
hashing
A generic constructor that builds a hash object from the algorithm name as a string: hashlib.new('sha256') is the same as hashlib.sha256().
Syntax
hashlib.new(name, data=b'', *, usedforsecurity=True)
It is meant for when the algorithm comes from a config file or a command-line argument; when the name is known in advance, the named constructor is faster and safer. The name is case-insensitive ('SHA256' works too), and an unknown one raises ValueError (the message varies by version: in 3.15 it is “unsupported hash algorithm”). The set of names depends on the OpenSSL build: only hashlib.algorithms_guaranteed is always there, while algorithms_available differs between machines — an algorithm you found locally may be missing on the server.
Examples
import hashlib
h = hashlib.new('SHA256', b'abc')
print(h.name) # → sha256
print(h.hexdigest()[:16]) # → ba7816bf8f01cfea
import hashlib
try:
hashlib.new('sha257')
except ValueError as e:
print(e) # → sha257 — «unsupported hash type», с 3.15 «unsupported hash algorithm»
See also
Common errors
Open in the full glossarydocs.python.orgReport an inaccuracy