DEV Community

SEMIU AMAO
SEMIU AMAO

Posted on

Password Encryption with Hash Function in Python

Securing access to the secured part of applications or devices is commonly achieved by simply authenticating the users by requesting for the username and the password which is stored in the external database (either on the cloud or on local device but separated from the application using the data). The storage of the database in most cases are secured from unauthorised access.

Sample Database

Considering the information above supplied by different users and this is stored in a cloud database (e.g. Google firestore) as it is using the code below.

user= input ('Enter Username:')
pasw= input('enter password: ')
bs = db.document('SECURE_APP').collection('USERS').add({
'Username': user,
'Password': pasw
})

Authenticating a user after creating the first credentials would follow this code:

u= userdatabase.get('Username')
p= userdatabase.get('Password')
user= input ('Enter Username:')
pasw= input('enter password: ')
if pasw == p :
print('Correct!')
else:
print('Fail')

This implies that the database administrator and those who have authority to such database can know the password of every users. That is not the only risk, a potential hacker that gains view only access into such database has won jackpot. This implies that all the users credentials into the application are exposed.

In order to secure the users information when it is stored in the database, some important information such as the password, pin-code etc are encrypted before storing into the database. One of the simplest and secured way of encrypting the data before storing into the database is using hash function.

What is Hash Function ?
It is algorithm used in cryptography for data encryption as it takes data of arbitrary length (as input) and produce the fixed length of encrypted data as output. Hash function is irreversible. This implies that gaining access to the output of an Hash function, it is mostly impossible to get the input data.
As stated earlier, the data supplied for the password field can be hashed before writing to the database. Therefore, the following algorithm will be followed to store and retrieve the user’s detail.

-Take username and password
-Hash the password
-Store username and based password

Python code:

user= input ('Enter Username:')
pasw= input('enter password: ')
bs = db.document('SECURE_APP').collection('USERS').add({
'Username': user,
'Password': hash(pasw)
})

Authentication
-Retrieve the username and hashed password from the database
-Take the username and password from the input device
-Hash the password
-Compare the 2 hashed passwords together, if the same

Python Code:

u= userdatabase.get('Username')
p= userdatabase.get('Password')
user= input ('Enter Username:')
pasw= input('enter password: ')
hp = hash(pasw)
if hp == int(p) :
print('Correct!')
else:
print('Fail')

Top comments (0)