DEV Community

Cover image for python hashing
tcs224
tcs224

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

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

"Hello world" hashed becomes

'64ec88ca00b268e5ba1a35678a1b5316d212f4f366b2477232534a8aeca37f3c'.

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

'2161447856ce2af91e8b7efa6cfbad572f775609925f492e962ba8a7408d6b19'

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)