Fix Python – Salt and hash a password in Python


Asked By – Chris Dutrow

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()
hashed_password =  base64.urlsafe_b64encode(t_sha.digest())

Now we will see solution for issue: Salt and hash a password in Python


EDIT: This answer is wrong. A single iteration of SHA512 is fast, which makes it inappropriate for use as a password hashing function. Use one of the other answers here instead.

Looks fine by me. However, I’m pretty sure you don’t actually need base64. You could just do this:

import hashlib, uuid
salt = uuid.uuid4().hex
hashed_password = hashlib.sha512(password + salt).hexdigest()

If it doesn’t create difficulties, you can get slightly more efficient storage in your database by storing the salt and hashed password as raw bytes rather than hex strings. To do so, replace hex with bytes and hexdigest with digest.

This question is answered By – Taymon

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0