Python 相等字符串不';我不能回到真实的状态

Python 相等字符串不';我不能回到真实的状态,python,dictionary,hash,Python,Dictionary,Hash,我已经开始学习Python,我从《暴力Python》一书开始。在第一章中,描述了一个脚本,该脚本使用crypt类来破解基于*nix的密码散列。代码如下: import crypt def testPass(cryptPass): salt = cryptPass[0:2] dictFile = open('dictionary.txt','r') for word in dictFile.readlines(): word = word.strip('\n

我已经开始学习Python,我从《暴力Python》一书开始。在第一章中,描述了一个脚本,该脚本使用
crypt
类来破解基于*nix的密码散列。代码如下:

import crypt
def testPass(cryptPass):
    salt = cryptPass[0:2]
    dictFile = open('dictionary.txt','r')
    for word in dictFile.readlines():
        word = word.strip('\n')
        cryptWord = crypt.crypt(word,salt)
        print cryptPass+":"cryptWord
        if(cryptPass == cryptWord):
            print "[+] Password found : "+word
            return

print "[-] Password Not Found.\n"
return
def main():
    passFile = open('passwords.txt')
    for line in passFile.readlines():
        if ":" in line:
            user = line.split(':')[0]
            cryptPass = line.split(':')[1].strip(' ')
            print "[*] Cracking Password For: "+user
            testPass(cryptPass)
if __name__ == "__main__":
main()
我有一个passwords.txt文件,其中包含username:password(password hash)字符串,还有一个名为dictionary.txt的文件,其中包含字典单词。这些是passwords.txt文件的内容:

apple:HXJintBqUVCEY
mango:HXInAjNhZF7YA
banana:HXKfazJbFHORc
grapes:HXtZSWbomS0xQ
和dictionary.txt:

apple
abcd
efgh
ijkl
mnop

当我打印它们时,从testpass()方法计算的密码散列和从passwords.txt计算的用户名apple的密码散列是相等的。但是这里所有4个用户名的输出都是“[-]找不到密码”。为什么==测试在这里失败?

也许行的末尾有一个尾随的
\n
。尝试更改:

        cryptPass = line.split(':')[1].strip(' ')
致:

或者更简单(如评论中所述):


使用
.strip('\n')
将比链接两个
strip
方法调用更简单。
.strip()
将对换行符和空格hanks都适用。这就成功了,来自java的后台从未想过结尾会有尾随。不客气@MosesKoledoye你是对的,我补充道。我也保留了原文,因为它解释了如何更好地解决问题。
        cryptPass = line.split(':')[1].strip('\n').strip(' ')
        cryptPass = line.split(':')[1].strip()