问题描述
一直在检查我如何根据明文密码验证加密密码,明文密码存储在我的桌面上名为 pswd0.lst 的文件中。如果我提供它的散列版本,我想检查是否可以在文件中找到名为“test3”的密码,在这种情况下它是 oHZcndn1xmAvs
。谁能帮忙?
import os,sys
import getopt
import crypt
def checkPassword(pswd,cpswd):
""" Check if `cpwsd` an encrypted version is of `pswd`.
Return `True` or `False`
"""
try:
cryptedpass = crypt.crypt(pswd,cpswd) == cpswd
return cryptedpass
except KeyError:
return 0 # no match
def readPasswordList(fname):
""" Read the passwords of the file named by 'fname'.
Return `list or strings`,the password-list
"""
file = open(fname,'r')
data = file.read()
return data
def checkPasswords(cpswd,fname):
""" Check crypted `cpswd` against the passwords of the file named by `fname`.
Return `string` or None,password if found.
"""
file = open(fname,'r')
data = file.read()
passw = crypt.crypt(data,cpswd) == data
return passw
if __name__ == '__main__':
fname = ''
opts,args = getopt.getopt(sys.argv[1:],'Vf:',[])
for opt,arg in opts:
if opt == '-f': fname = arg
if len(args) != 1:
print('Usage: {} [-v] [-f <fname>] <cpswd>'.format(sys.argv[0]))
sys.exit(0)
cpswd = args[0]
pswd = checkPasswords(cpswd,fname)
if pswd:
print("Pass for '{}' is '{}'".format(
cpswd,fname))
else:
print("Pass for '{}' not found".format(
cpswd,fname))```
解决方法
您至少有两个问题:
- 读取文件时,会将整个文件作为一个长字符串读取。您不会将其拆分为单独的行。
- 您忘记了 crypt() 函数添加了一个盐,因此两个 crypt() 函数会对相同的密码产生不同的结果。
我在谷歌上搜索了“python crypt”,瞧,第一个结果:https://docs.python.org/3/library/crypt.html