为什么我的两个python字符串在程序中不相等,但在解释器中相等?

为什么我的两个python字符串在程序中不相等,但在解释器中相等?,python,string,hash,equality,Python,String,Hash,Equality,我正在尝试使用python编写一个聊天服务器。我使用SHA1散列来验证用户,并将用户存储的散列与给定密码的散列进行比较,如果它们相同,那么我应该验证用户 我的哈希函数如下所示: def sha1_encode(string): import hashlib return hashlib.sha1(bytes(string)).hexdigest() 我的验证用户如下所示: def validate_user(self, user, password): if user

我正在尝试使用python编写一个聊天服务器。我使用SHA1散列来验证用户,并将用户存储的散列与给定密码的散列进行比较,如果它们相同,那么我应该验证用户

我的哈希函数如下所示:

def sha1_encode(string):
    import hashlib
    return hashlib.sha1(bytes(string)).hexdigest()
我的验证用户如下所示:

def validate_user(self, user, password):
    if user in self.users:
        print "user exists"
        #Get the saved SHA1 hash and see if it matches the hash of the given
        #password
        print "sha", sha1_encode(password)
        print "stored", self.users[user]
        print "equal", self.users[user] == sha1_encode(password)
        print type(self.users[user])
        print type(sha1_encode(password))
        if str(self.users[user]) == str(sha1_encode(password)):
            print "validate loop entered"
            return True
    else:
        return False
当我与我知道在列表中的用户一起运行时,我得到以下输出:

user exists
sha 61503cfe0803f3a3b964b46a405f7828fd72b1f7
stored 61503cfe0803f3a3b964b46a405f7828fd72b1f7

equal False
<type 'str'>
<type 'str'>

在这一点上,我很困惑为什么它在函数中不报告true,在解释器中报告true,特别是因为我似乎在用不同的变量名做同样的事情。谁能给我解释一下发生了什么事?任何帮助都将不胜感激

> P> >在这里,但是根据您的输出,在您的存储密码列表中可能有尾部“\n”,因此在

后输出中的空行。
print "stored", self.users[user]
你可以试试

print "equal", self.users[user].strip() == sha1_encode(password)

看看这是否解决了你的问题。调用将删除尾随字符

我不知道这个方法是如何工作的,所以这只是一个粗略的猜测,但它可能与你称之为twiceonprinting sha和once做比较有关。尝试将其返回值赋给一个变量,然后进行比较。@Lafexlos如果您认为有帮助,我可以发布更多代码,但这正是我认为相关的内容。我确实试过了,但也遇到了同样的错误。也不应该不管我调用它多少次,因为对于同一个字符串,SHA1散列应该总是相同的吗?顺便说一句,您的代码是错误的,并且假设Python 2;ByteString在Python3上不起作用;您需要提供一个编码。此外,像这样使用SHA1作为密码和使用MD5一样是错误的,只需谷歌一下;相反,我建议您查看passlib及其提供的函数,它看起来像是存储的哈希在末尾有一个换行符。尝试在每个字符串的末尾与.strip进行比较。此外,在调试时,请打印字符串的repr:print stored,reprself.users[user]或更好的方法是让sha1_encode返回一个剥离值,而不是打印字符串的repr
print "equal", self.users[user].strip() == sha1_encode(password)