Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Salt and hash a password in Python

This code is supposed to hash a password with a salt. The salt and hashed password are being saved in the database. The password itself is not.

Given the sensitive nature of the operation, I wanted to make sure everything was kosher.

import hashlib import base64 import uuid  password = 'test_password' salt     = base64.urlsafe_b64encode(uuid.uuid4().bytes)   t_sha = hashlib.sha512() t_sha.update(password+salt) hashed_password =  base64.urlsafe_b64encode(t_sha.digest()) 
like image 604
Chris Dutrow Avatar asked Mar 07 '12 00:03

Chris Dutrow


People also ask

What is hash and salt of a password?

Hashing is a one-way function where data is mapped to a fixed-length value. Hashing is primarily used for authentication. Salting is an additional step during hashing, typically seen in association to hashed passwords, that adds an additional value to the end of the password that changes the hash value produced.

What is Bcrypt Python?

The bcrypt is a password hashing function designed by Niels Provos and David Mazières, based on the Blowfish cipher. The bcrypt function is the default password hash algorithm for OpenBSD. There are implementations of bcrypt for C, C++, C#, Java, JavaScript, PHP, Python and other languages.


1 Answers

Based on the other answers to this question, I've implemented a new approach using bcrypt.

Why use bcrypt

If I understand correctly, the argument to use bcrypt over SHA512 is that bcrypt is designed to be slow. bcrypt also has an option to adjust how slow you want it to be when generating the hashed password for the first time:

# The '12' is the number that dictates the 'slowness' bcrypt.hashpw(password, bcrypt.gensalt( 12 )) 

Slow is desirable because if a malicious party gets their hands on the table containing hashed passwords, then it is much more difficult to brute force them.

Implementation

def get_hashed_password(plain_text_password):     # Hash a password for the first time     #   (Using bcrypt, the salt is saved into the hash itself)     return bcrypt.hashpw(plain_text_password, bcrypt.gensalt())  def check_password(plain_text_password, hashed_password):     # Check hashed password. Using bcrypt, the salt is saved into the hash itself     return bcrypt.checkpw(plain_text_password, hashed_password) 

Notes

I was able to install the library pretty easily in a linux system using:

pip install py-bcrypt 

However, I had more trouble installing it on my windows systems. It appears to need a patch. See this Stack Overflow question: py-bcrypt installing on win 7 64bit python

like image 69
Chris Dutrow Avatar answered Sep 28 '22 17:09

Chris Dutrow