Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the output of werkzeugs `generate_password_hash` not constant?

When I run werkzeug.security.generate_password_hash("Same password") (docs) multiple times, the output is different each time.

What am I doing wrong? Why is it not constant?

like image 637
Shankar ARUL Avatar asked May 02 '14 16:05

Shankar ARUL


People also ask

What is Check_password_hash?

check_password_hash (pwhash, password)[source] check a password against a given salted and hashed password value. In order to support unsalted legacy passwords this method supports plain text passwords, md5 and sha1 hashes (both salted and unsalted). Returns True if the password matched, False otherwise.

What is Generate_password_hash?

generate_password_hash. generate_password_hash takes plaintext password, hashing method and salt length as an input to produce hashed password. By default it produces salt string with length 8.

What is from werkzeug utils import Secure_filename?

secure_filename. Pass it a filename and it will return a secure version of it. This filename can then safely be stored on a regular file system and passed to os.


1 Answers

The password is salted, yes. The salt is added to the password before hashing, to ensure that the hash isn't useable in a rainbow table attack.

Because the salt is randomly generated each time you call the function, the resulting password hash is also different. The returned hash includes the generated salt so that can still correctly verify the password.

Demo:

>>> from werkzeug.security import generate_password_hash >>> generate_password_hash('foobar') 'pbkdf2:sha1:1000$tYqN0VeL$2ee2568465fa30c1e6680196f8bb9eb0d2ca072d' >>> generate_password_hash('foobar') 'pbkdf2:sha1:1000$XHj5nlLU$bb9a81bc54e7d6e11d9ab212cd143e768ea6225d' 

These two strings differ; but contain enough information to verify the password because the generated salt is included in each:

# pbkdf2:sha1:1000$tYqN0VeL$2ee2568465fa30c1e6680196f8bb9eb0d2ca072d   ^^^^^^^^^^^^^^^^   salt   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^       algo info    ^^^^^^^^        actual hash of the password   (PBKDF2 applied SHA1 1000 times) 

Because the random salt is tYqN0VeL for one and XHj5nlLU, the resulting hash is also different.

The foobar password can still be verified against either hash:

>>> from werkzeug.security import check_password_hash >>> check_password_hash('pbkdf2:sha1:1000$tYqN0VeL$2ee2568465fa30c1e6680196f8bb9eb0d2ca072d', 'foobar') True >>> check_password_hash('pbkdf2:sha1:1000$XHj5nlLU$bb9a81bc54e7d6e11d9ab212cd143e768ea6225d', 'foobar') True 

Also see

  • Can you help me understand what a cryptographic “salt” is? (Cryptography.SE)
  • Why is using salt more secure? (Security.SE)
like image 180
Martijn Pieters Avatar answered Sep 28 '22 02:09

Martijn Pieters