Why are my two python strings not equal in my prog

2020-02-15 07:36发布

问题:

I'm trying to write a chat server using python. I am using SHA1 hash to validate users and comparing the stored hash for the user to the hash of the given password and if they are the same then I should validate the user.

My hash function looks like this:

def sha1_encode(string):
    import hashlib
    return hashlib.sha1(bytes(string)).hexdigest()

and my validate user looks like this:

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

when I run this with a user I know is in the list, I get this output:

user exists
sha 61503cfe0803f3a3b964b46a405f7828fd72b1f7
stored 61503cfe0803f3a3b964b46a405f7828fd72b1f7

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

so I know both of them are strings and I know that they are both the same thing but for some reason return false. I originally was questioning the objects being of different types but that doesn't seem to be the case.

So then I tried to copy these strings into the interpreter and check if they were actually equal:

In [1]: x = '61503cfe0803f3a3b964b46a405f7828fd72b1f7'

In [2]: y = '61503cfe0803f3a3b964b46a405f7828fd72b1f7'

In [3]: x == y 
Out[3]: True

And at this point I'm confused why it's not reporting true in the function and reporting true in the interpreter, especially cause it seems like I am doing the same exact thing just with different variable names. Could anyone explain to me whats going on? Any help would be greatly appreciated.

回答1:

Just taking a stab here, but based on your output it looks like there might be a trailing '\n' in your stored password list thus the blank line in the output after

print "stored", self.users[user]

You could try

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

to see if that takes care of your problem. The call will remove trailing characters.