2013-08-22 254 views
1

目前我的應用程序在提交時正確地存儲密碼,但它沒有被散列並且以明文存儲。安全地存儲密碼哈希django

我的觀點:

def Registration(request): 
    RegForm = RegistrationForm(request.POST or None) 
    if request.method == 'POST': 
     if RegForm.is_valid(): 
      clearUserName = RegForm.cleaned_data['userNm'] 
      clearPassNoHash = RegForm.cleaned_data['userPass'] 
      clearPass = bcrypt.hashpw(clearPassNoHash.encode("utf-8"), bcrypt.gensalt(14)) 
      RegForm.save() 
      try: 
       return HttpResponseRedirect('/Newuser/?userNm=' + clearUserName) 
      except: 
       raise ValidationError(('Invalid request'), code='300')  
    else: 
     RegForm = RegistrationForm() 

     return render(request, 'VA/reuse/register.html', { 
      'RegForm': RegForm 
     }) 

形式

class RegistrationForm(ModelForm): 
    userPass = forms.CharField(widget=forms.PasswordInput, label='Password') 
    class Meta: 
     model = Client 
     fields = ['userNm','userPass'] 

models.py

class Client(models.Model): 
    userNm = models.EmailField(verbose_name="Email",max_length=50,unique=True) #userNm = <user's email> 
    userPass = models.CharField(verbose_name="Password", max_length=50) 

問題是與clearPass中似乎認爲它只是發送t他的價值是clearPassNoHash,因爲它的價值是.cleaned_data[]的一部分。任何想法我做錯了什麼?我希望得到一些幫助,正確實施這個以散列通行證。

謝謝

回答

1

您只是將值分配給變量。你應該將它分配到表格中:

if RegForm.is_valid(): 
     clearUserName = RegForm.cleaned_data['userNm'] 
     clearPassNoHash = RegForm.cleaned_data['userPass'] 
     RegForm.userPass = bcrypt.hashpw(clearPassNoHash.encode("utf-8"), bcrypt.gensalt(14)) 
     RegForm.save() 
+0

不幸的是,我想這一點 - 它提交的形式,但形式包含非散列,明文密碼。我也嘗試過:'userPassHashed = bcrypt.hashpw(RegForm.cleaned_data ['userPass']。encode(「utf-8」),bcrypt.gensalt(14))'但是這也行不通。有什麼想法嗎? – CodeTalk

0

我有類似的問題。我的解決方案是在我的models.py中定義一個方法,並調用該方法來散列我的純文本密碼。這裏是我的代碼:

#models.py 
def hash_password(password): 
#since our user model is from AbstractBaseUser, we need to manually hash passwords 
    hashed = make_password(password) #returns PBKDF2 hashed password 
    return hashed 

#views.py 
#encrypt plain password    
form.instance.password = hash_password(clean['password']) 

您沒有使用此(PBKDF2)散列算法,你可以使用一個過你想要(例如,您的Bcrypt算法)的。只要你返回哈希值,你應該很好。您可以使用的第二種解決方案是內置set_password,但我個人從未使用它。

0

我遇到類似的問題,並認爲在提交之前實例化的新用戶解決了這一問題對我來說:

def Registration(request): 
    RegForm = RegistrationForm(request.POST or None) 
    if request.method == 'POST': 
     if RegForm.is_valid(): 
      new_user = RegForm.save(commit=False) 
      new_user.userNm = RegForm.cleaned_data['userNm'] 
      new_user.userPass = bcrypt.hashpw(
       RegForm.cleaned_data['userPass'].encode("utf-8"), 
       bcrypt.gensalt(14)) 
      new_user.save() 
      try: 
       return HttpResponseRedirect('/Newuser/?userNm=' + clearUserName) 
      except: 
       raise ValidationError(('Invalid request'), code='300')  
    else: 
     RegForm = RegistrationForm() 

     return render(request, 'VA/reuse/register.html', { 
      'RegForm': RegForm 
     })