简体   繁体   中英

Django : crypt password with SHA1

I want to reuse an old database for a project. All the passwords in this database are crypted with sha1. That's why I'm trying to crypt password with sha1 in django. I tried something with the hashlib library but it doesn't work. This is my code: serializer.py:

from rest_framework import serializers
import hashlib
from .models import memberArea, category, product, byProduct, order, orderDetail

class RegistrationSerializer(serializers.ModelSerializer):

    password2 = serializers.CharField(style={'input-type' : 'password'}, write_only=True) #The field will be hidden from the user

    class Meta:
        model = memberArea
        fields = ['name', 'email', 'phone', 'password', 'password2', 'deliveryAddress', 'postalCode', 'city']
        extra_kwargs = {
            'password': {'write_only':True}, #For security to hide the password (we can't read it)
        }
    
    def save(self):
        account = memberArea(
            name = self.validated_data['name'],
            email = self.validated_data['email'],
            phone = self.validated_data['phone'],
            deliveryAddress = self.validated_data['deliveryAddress'],
            postalCode = self.validated_data['postalCode'],
            city = self.validated_data['city'],
        )
        password = self.validated_data['password']
        password2 = self.validated_data['password2']

        if password != password2:
            raise serializers.ValidationError({'password': 'Passwords must match !'})
        password = hashlib.sha1(password)
        account.password = password
        account.save()
        return account

views.py:

...
from .serializers import RegistrationSerializer
...
@api_view(['POST', ])
def register(request):
    if request.method == 'POST':
        serializer = RegistrationSerializer(data=request.data)
        data = {}
        if serializer.is_valid(): #Then we have access to the validated data in the file serializer.py
            account = serializer.save() #Call the save method that we built into serializer.py file (def save())
            data['response'] = "Successfully registered a new user !"
            data['name'] =  account.name
            data['email'] =  account.email
            data['phone'] =  account.phone
            data['deliveryAddress'] =  account.deliveryAddress
            data['postalCode'] =  account.postalCode
            data['city'] =  account.city
        else : 
            data['error'] = serializer.errors #Return the errors that we raised in the serializer.py file
        return Response(data)

When I'm running my code I get this error: Unicode-objects must be encoded before hashing Thank's by advance for your help.

Your error is in serializer.py ; you can't call hashlib.sha1 on an unencoded string. What you probably want to do is replace this line:

password = hashlib.sha1(password)

with this:

password = hashlib.sha1(password.encode('utf-8'))

If you want the password as a string, then the line should look like this:

password = hashlib.sha1(password.encode('utf-8')).hexdigest()

There's an entire section in the documentation about using/upgrading accounts with different hashers. It is a little more work in the beginning to migrate old password fields or password fields that were not created by Django.

From the looks that you accepted an answer that stores the plain hexdigest in the password field, without a crypt method identifier, I assume your old database isn't Django's, because Django will prepend sha1$ to the hexdigest.

If your database is indeed an old Django database, then it's very likely just changing the password hashers in settings.py will already work:

PASSWORD_HASHERS = [
    'django.contrib.auth.hashers.PBKDF2PasswordHasher',
    'django.contrib.auth.hashers.SHA1PasswordHasher',  # Or, if even older:
    'django.contrib.auth.hashers.UnsaltedSHA1PasswordHasher',
]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM