哈希比较总是返回fals

2024-04-16 22:43:44 发布

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

我已经检查了所有其他的答案,但没有任何工作,不管我提供什么字符串它总是返回假。你知道吗

import hashlib

class User:
    def __init__(self, username,password):
        self.username = username
        ''' Password will be encrypted , create user'''
        self.password = self._encrypt_pw(password)
        self.is_logged = False

    def _encrypt_pw(self,password):
        'encrypt password and return SHA'
        hash_string = (self.username+password)
        hash_string = hash_string.encode("utf-8")
        return hashlib.sha256(hash_string).hexdigest

    def check_password(self,password):
        'return true if password is true for this user or false'
        encrypted = self._encrypt_pw(password)
        return encrypted == self.password 

下面是运行的代码。你知道吗

Python 3.7.3 (v3.7.3:ef4ec6ed12, Mar 25 2019, 21:26:53) [MSC v.1916 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> from user import User
>>> u = User("abc","abc")
>>> u.password
<built-in method hexdigest of _hashlib.HASH object at 0x036BBCC8>
>>> u.password()
'bbb59da3af939f7af5f360f2ceb80a496e3bae1cd87dde426db0ae40677e1c2c'
>>> u.check_password("abc")
False

当我 放

return encrypted.digest() == self.password.digest(),

它返回错误

AttributeError: 'builtin_function_or_method' object has no attribute 'digest'

Tags: orselfstringreturndefusernamepasswordhash