如何对照文件(.lst)中存储的明文密码检查加密密码?

2024-10-03 06:21:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我一直在检查如何根据明文密码验证加密密码,明文密码存储在我桌面上名为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))```

Tags: oftheimport密码datareturnifdef
1条回答
网友
1楼 · 发布于 2024-10-03 06:21:33

您至少有两个问题:

  1. 读取文件时,将整个文件作为一个长字符串读取。您不能将其拆分为单独的行
  2. 您忘记了crypt()函数添加了salt,因此两个crypt()函数将为同一密码生成不同的结果

我在谷歌上搜索了“pythoncrypt”,瞧,第一个结果是:https://docs.python.org/3/library/crypt.html

相关问题 更多 >