Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to encrypt to Django default pbkdf2_sha256 encryption?

I want to encrypt the user input password to compare with the original password in some view. I tried importing and apply encrypt method:

import passlib.hash.django_pbkdf2_sha256

But it doesn't have that module?

like image 361
pynovice Avatar asked Oct 28 '25 12:10

pynovice


2 Answers

You may be looking for set_password

from models import User
new_user = User.objects.create(username='new_user', email='[email protected]')
new_user.set_password('newpassword')

Alternatively, you can use make_password

from django.contrib.auth.hashers import make_password
from models import User
first_pass = User.objects.all()[0].password.split('$')
hasher = first_pass[0]
salt = first_pass[1]  # grabbing salt from the first password of the database
make_password('newpassword', salt, hasher)
like image 152
Joseph Coco Avatar answered Oct 30 '25 03:10

Joseph Coco


You should just use the authenticate method from django.contrib.auth:

test_user = authenticate(username=..., password=...)

If the credentials are valid, a new user will be returned, but this will not change the currently logged-in user. This will still work if some user uses a different encryption scheme, or if you are using custom authentication backends.

If for some reason you still need to reproduce Django's encryption, you can use django.utils.crypto.pbkdf2, but again, you will probably be better off using the higher level check_password function from django.contrib.auth.hashers:

check_password(new_password, encoded_password)
like image 33
Nicolas Cortot Avatar answered Oct 30 '25 05:10

Nicolas Cortot



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!