如何让 crypt 模块仅在参数值与给定值相同时才工作?

how to let crypt module only work when paramater values are identical to the given ones?

我一直在努力弄清楚如何让此代码仅在值与给定的值匹配时才起作用,例如,ubuntu。该代码有效,但当我给另一个 pass/hash 而不是 test/npDnXtpN5py4 时,它仍然说密码与原始密码匹配。谁能帮忙?问候。

import os, sys
import getopt
import pwd
import crypt


def checkPassword(pswd, cpswd):
    """ Check if `cpwsd` an encrypted version is of `pswd`.
        Return `True` of `False`
    """
    try:
        cpswd = 'npDnXtpN5py4U'
        pswd = 'test'
        cryptedpassword = crypt.crypt(pswd, cpswd)
        return cpswd == cryptedpassword
    except KeyError:
        return 0 # no such pw

if __name__ == '__main__':
    opts, args = getopt.getopt(sys.argv[1:], 'V', [])
    if len(args) != 2:
        print('Usage: {} [-v] <cpswd> <pswd>'.format(sys.argv[0]))
        sys.exit(0)

    cpswd, pswd = args[0], args[1]
    res = checkPassword(pswd, cpswd)
    if res:
        print("Pass for '{}' is '{}'".format(
            cpswd, pswd))
    else:
        print("Pass for '{}' is not '{}'".format(
            cpswd, pswd))

checkPassword(pswd, cpswd)中的代码:

cpswd = 'npDnXtpN5py4U'
pswd = 'test'

...将覆盖函数的参数,也称为 pswdcpswd,因此它实质上将测试是否 crypt.crypt('test', 'npDnXtpN5py4U') == 'npDnXtpN5py4U'.

显然,'npDnXtpN5py4U' 是加密字符串 'test' 的可能结果,因此调用 crypt.crypt('test', 'npDnXtpN5py4U') 将始终 return 它的最后一个参数:

>>> import crypt
>>> cpswd = 'npDnXtpN5py4U'
>>> pswd = 'test'
>>> crypt.crypt(pswd, cpswd)
'npDnXtpN5py4U'

总而言之,问题是这个函数完全忽略了传递给它的参数,并且总是return相同的结果。