DEV Community

Cover image for python hashing

Posted on


python hashing

In Python, as in many other languages, you can make use of a hash function. A hash function is a one way function that takes input of a variable length ( a byte string ) and converts it to a fixed length sequence.

So if f is a hashing function, calculating f(x) is easy but the other way around will take years and years. Please note that hashing is not encryption, it doesn't make use of (private) keys.

hash function

This is very useful when you want to store passwords on a computer, to prevent leaks you hash them. In practice this doesn't always happen, and some companies store passwords in plain text which is a security risk.

Before playing with hashing, you should know the basics of Python


Example: if you use the sha256 hashing function, with several inputs:

"Hello world" hashed becomes


If instead you use "Hello World" (capital W) you get:


So a small change in input is a large change in output. In Python you can do hashing with the module hashlib.

>>> import hashlib
>>> m = hashlib.sha256()
>>> m.update(b"Hello World")
>>> m.hexdigest()

There are many hashing algorithms, to see the ones included with your hashlib version type

>>> import hashlib
>>> print(hashlib.algorithms_available)
{'blake2b512', 'shake_256', 'sha3-224', 'blake2s256', 'sha3-512', 'shake256', 'sha3-256', 'shake128', 'sha3_224', 'sha1', 'sha512', 'sha512-256', 'sha224', 'blake2b', 'shake_128', 'sha384', 'md5-sha1', 'md4', 'sha512-224', 'whirlpool', 'sm3', 'md5', 'sha3-384', 'sha3_256', 'sha256', 'sha3_384', 'sha3_512', 'blake2s', 'ripemd160'}

If you run the code below, you'll see a different hash for the same output, because they are different hashing algorithms.

>>> print(hashlib.md5(b'Hello World').hexdigest())
>>> print(hashlib.sha1(b'Hello World').hexdigest())
>>> print(hashlib.sha224(b'Hello World').hexdigest())
>>> print(hashlib.sha256(b'Hello World').hexdigest())
>>> print(hashlib.sha384(b'Hello World').hexdigest())
>>> print(hashlib.sha512(b'Hello World').hexdigest())
>>> print(hashlib.blake2s(b'Hello World').hexdigest())

Be careful with using md5 and sha1 as they are deprecated.

Related links:

Top comments (0)

An Animated Guide to Node.js Event Loop

Node.js doesnโ€™t stop from running other operations because of Libuv, a C++ library responsible for the event loop and asynchronously handling tasks such as network requests, DNS resolution, file system operations, data encryption, etc.

What happens under the hood when Node.js works on tasks such as database queries? We will explore it by following this piece of code step by step.