3

I have a password hash generated by Django. I want to log in a user with this password hash from Flask. How can I verify the password in Flask?

from django.contrib.auth import hashers
hash = hashers.make_password('pasword')
# pbkdf2_sha256$20000$3RFHVUvhZbu5$llCkkBhVqeh69KSETtH8gK5iTQVy2guwSSyTeGyguxE='

PASSWORD_HASHERS = (
    'django.contrib.auth.hashers.PBKDF2PasswordHasher',
    'django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher',
    'django.contrib.auth.hashers.BCryptSHA256PasswordHasher',
    'django.contrib.auth.hashers.BCryptPasswordHasher',
    'django.contrib.auth.hashers.SHA1PasswordHasher',
    'django.contrib.auth.hashers.MD5PasswordHasher',
    'django.contrib.auth.hashers.CryptPasswordHasher',
)
davidism
  • 121,510
  • 29
  • 395
  • 339
Sung Jin O
  • 171
  • 1
  • 2
  • 10
  • 1
    Please read up on the difference between hashing and encryption (for example here http://stackoverflow.com/questions/4948322/fundamental-difference-between-hashing-and-encryption-algorithms) – reto Jun 11 '15 at 11:47
  • Long story short (with some crazy simplifications): It is hard to get the value back directly from this hash, the typical way is to enter the same password and hash it and see if the hashes are the same. – reto Jun 11 '15 at 11:48

1 Answers1

11

You can use the passlib package to work with password hashes. It comes with support for Django's hash format. Your example hash uses pbkdf2_sha256, so use the corresponding passlib hash:

from passlib.hash import django_pbkdf2_sha256
hash = 'pbkdf2_sha256$20000$3RFHVUvhZbu5$llCkkBhVqeh69KSETtH8gK5iTQVy2guwSSyTeGyguxE='
user_input = 'password'
django_pbkdf2_sha256.verify(user_input, hash)

If you want to support multiple formats, like Django does, you can use the pre-configured Django context, or make your own with whatever order is in Django's PASSWORD_HASHERS.

from passlib.apps import django_context
hash = 'pbkdf2_sha256$20000$3RFHVUvhZbu5$llCkkBhVqeh69KSETtH8gK5iTQVy2guwSSyTeGyguxE='
user_input = 'password'
django_context.verify(user_input, hash)
davidism
  • 121,510
  • 29
  • 395
  • 339