Django:使用 SHA1 加密密码

Django : crypt password with SHA1

我想为项目重用旧数据库。此数据库中的所有密码均使用 sha1 加密。 这就是为什么我试图在 django 中使用 sha1 加密密码。 我尝试了一些 hashlib 库,但它不起作用。 这是我的代码: 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)

当我 运行 我的代码时,我收到此错误:Unicode-objects must be encoded before hashing 预先感谢您的帮助。

你的错误在serializer.py;您不能在未编码的字符串上调用 hashlib.sha1。您可能想要做的是替换此行:

password = hashlib.sha1(password)

有了这个:

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

如果您希望密码为字符串,则该行应如下所示:

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

有一个 entire section in the documentation 关于 using/upgrading 个具有不同散列器的帐户。迁移旧的密码字段或不是由 Django 创建的密码字段在开始时需要做更多的工作。

从您接受的答案来看,该答案在密码字段中存储了纯十六进制摘要,没有加密方法标识符,我假设您的旧数据库不是 Django 的,因为 Django 会将 sha1$ 添加到十六进制。

如果您的数据库确实是一个旧的 Django 数据库,那么很可能只需更改 settings.py 中的密码哈希器就可以了:

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