All Courses

Hash Functions in Python

Shashank Shanu

2 years ago

• Introduction
• Hash Function
• Flowchart

Introduction

Python supports a Hash function which helps to map a large amount of data to a fixed value with a specified length. This function always ensures that an input results in the same output, which is known as a Hash sum. Hash sum helps to hold a characteristic with specific information.
It is impossible to revert this hash function, so we will almost never find a third-party attack like brute force. This kind of algorithm is also known as a one-way cryptographic algorithm.
Some of the main properties of an ideal cryptographic hash function are as follows –
• It is almost easy to compute the hash value for any given input.
• It is not feasible to generate the original input from a given hash value.
• It is not feasible to modify the input without changing the hash value.
• It is not feasible to find two different inputs with the same hash value.
Let’s take an example to get a better understanding
Example
In this example we will how it helps in matching passwords using characters in hexadecimal format.
``````import uuid
import hashlib

# userid is used to generate a random number
salt = uuid.uuid4().hex #salt is stored in hexadecimal value
return hashlib.sha256(salt.encode() + password.encode()).hexdigest() + ':' + salt

# for storing passwords hexdigest is used as an algorithm

print('String to store in the db is: ' + hashed_password)

else:
print('Sorry but the password does not match')
``````
Output:
``````Hello User, Please enter required password 123
Sorry but the password does not match

String to store in the db is: a53693b8e064159fc8ad2926405fa7ac878890072c75d6415b5c1eae772a3198:46c3623f467b42f69fb19e668f491214
``````
Now let’s try to understand with the help of a flowchart

Flowchart

The logic of this program is explained with the help of the following flowchart −
Here the password entered twice matches with the hash function. It ensures that the password entered twice is accurate, which helps in gathering useful data and save them in an encrypted format.