比较Strings Loop Python

时间:2017-03-21 17:13:41

标签: python python-3.x loops hash

我正在尝试创建一个循环来比较我已经创建的列表中的字符串。该列表是密码,密码与md5相同。我有一个执行散列的函数,另一个打印出两个密码的列表。新功能" findmd5"应该将密码列表的每个md5加密值与传入的加密字符串进行比较。" pass2check"是我试图在循环中使用的预定字符串,其md5值应该返回密码" football"。我的新功能中的代码非常不完整,因为我在接下来的步骤中迷失了......

import hashlib
passwordlist = ["password","123456","12345678","1234","qwerty","12345",
"baseball","football","letmein","monkey","abc123","mustang","michael"]

def makemd5(key_string):

    new_key_string = key_string.encode('utf-8')

    return (hashlib.md5 ( new_key_string ).hexdigest())

def createmd5list(passwordlist):

    for passlist in passwordlist:
        hashlist = makemd5(passlist)
        print (passlist,",",hashlist)

def findmd5(pass2check):

    for line in open(passwordlist + hashlist): 
        if pass2check in line:
            print(True)
        else:
            print(False)


def main():

    pass2check = "37b4e2d82900d5e94b8da524fbeb33c0"



main ()

2 个答案:

答案 0 :(得分:0)

你可以试试这个():

import hashlib
passwordlist = ["password","123456","12345678","1234","qwerty","12345",
"baseball","football","letmein","monkey","abc123","mustang","michael"]

def listOfHashs():
    return [hashlib.md5(item.encode('utf-8')).hexdigest() for item in passwordlist]

def main():
    pass2check = "37b4e2d82900d5e94b8da524fbeb33c0"
    index = listOfHashs().index(pass2check)
    print(passwordlist[index] if index >= 0 else "Hash not found !")

main()

在这个版本中,我试图修改你的代码:

import hashlib
passwordlist = ["password","123456","12345678","1234","qwerty","12345",
"baseball","football","letmein","monkey","abc123","mustang","michael"]

def makemd5(key_string):
    new_key_string = key_string.encode('utf-8')
    return (hashlib.md5 ( new_key_string ).hexdigest())

def createmd5list(passwordlist):
    hashlist = []
    for passlist in passwordlist:
        hashlist += [makemd5(passlist)]
    return hashlist

def findmd5(pass2check):
    for index, line in enumerate(createmd5list(passwordlist)): 
        if pass2check in line:
            return index
    return -1


def main():
    pass2check = "37b4e2d82900d5e94b8da524fbeb33c0"
    index = findmd5(pass2check)
    if index >= 0:
        print passwordlist[index]
    else:
        print "Hash not found !"

main()

答案 1 :(得分:0)

您无需创建散列密码列表。相反,您在列表推导中构建摘要和过滤器,最终列表仅包含有效的解决方案。

重新编写自己的代码,看起来像

import hashlib
passwordlist = ["password","123456","12345678","1234","qwerty","12345",
    "baseball","football","letmein","monkey","abc123","mustang","michael"]

def findmd5(pass2check):
    result = [password for password in passwordlist 
              if hashlib.md5(password).hexdigest() == pass2check
             ]
    if len(result):
        print("The answer is")
        for password in result:
            print(password)
    else:
        print("Password not found")

def main():

    pass2check = "37b4e2d82900d5e94b8da524fbeb33c0"
    findmd5(pass2check)


main ()

这将打印所有有效的解决方案