Flask Snippets

Snippets are unofficial and unmaintained.

This is an archived view of user-submitted snippets. Despite being hosted on the Flask site, they are not official. No Flask maintainer has curated or checked the snippets for security, correctness, or design.

Salted Passwords

Posted by Armin Ronacher on 2011-07-11 @ 21:09 and filed in Security

When you have user accounts and you give them passwords you really don't want to store them in the database unhashed. However just hashing the passwords is barely more secure because of Rainbow table attacks. What you want to do is to salt the passwords which means that instead of just hashing the password you hash the password + a salt. And you also don't just want to concatenate them but use HMAC. And because that's common and easy to make wrong, Werkzeug provides a helper for that which also generates a hash for you.

Here is how it works. The following example assumes that you use some class for your user object:

from werkzeug.security import generate_password_hash, \

class User(object):

    def __init__(self, username, password):
        self.username = username

    def set_password(self, password):
        self.pw_hash = generate_password_hash(password)

    def check_password(self, password):
        return check_password_hash(self.pw_hash, password)

And here is how it works:

>>> me = User('John Doe', 'default')
>>> me.pw_hash
>>> me.check_password('default')
>>> me.check_password('defaultx')

This snippet by Armin Ronacher can be used freely for anything you like. Consider it public domain.