姜戈 :带有SHA1的加密密码



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

文档中有一整节是关于使用/升级具有不同哈希器的帐户的。一开始要迁移旧的密码字段或不是由 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',
]

最新更新