Django:SHA1的密码

2024-06-16 10:45:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我想在项目中重用旧数据库。此数据库中的所有密码都使用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 谢谢你的帮助


Tags: thenamepyselfdataemailphoneaccount
2条回答

有一个entire section in the documentation关于使用/升级不同哈希程序的帐户。在开始迁移旧密码字段或不是由Django创建的密码字段时需要做更多的工作

看起来您接受了一个答案,该答案将普通的hexdigest存储在password字段中,没有crypt方法标识符,因此我假设您的旧数据库不是Django的,因为Django将在hexdigest前面加上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',
]

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

password = hashlib.sha1(password)

为此:

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

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

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

相关问题 更多 >