crypt —检查 Unix 密码的Function

源代码: Lib/crypt.py


该模块实现了* crypt(3) *例程的接口,该例程是基于修改后的 DES 算法的单向哈希函数;有关更多详细信息,请参见 Unix 手册页。可能的用途包括存储哈希密码,以便您可以在不存储实际密码的情况下检查密码,或try使用字典破解 Unix 密码。

注意,此模块的行为取决于正在运行的系统中* crypt(3) *例程的实际实现。因此,当前实现上可用的任何扩展也将在此模块上可用。

Availability:Unix。在 VxWorks 上不可用。

Hashing Methods

版本 3.3 中的新Function。

crypt模块定义了哈希方法列表(并非所有方法在所有平台上都可用):

3.7 版中的新Function。

Module Attributes

版本 3.3 中的新Function。

Module Functions

crypt模块定义以下Function:

通常pass将纯文本密码作为* word *传递,并将先前的crypt()调用的完整结果传递给密码,从而完成密码检查,该结果应与此调用的结果相同。

以字符串形式返回哈希密码,该密码由与 salt 相同字母的字符组成。

由于一些* crypt(3) extensions 允许 salt *中具有不同大小的不同值,因此建议在检查密码时使用完全加密的密码作为盐。

在版本 3.3 中进行了更改:除* salt *的字符串外,还接受crypt.METHOD_*个值。

返回值是一个字符串,适合作为参数传递给crypt()

版本 3.3 中的新Function。

在 3.7 版中进行了更改:添加了* rounds *参数。

Examples

一个简单的示例说明典型用法(需要进行恒定时间比较操作以限制对定时攻击的暴露.hmac.compare_digest()适用于此目的):

import pwd
import crypt
import getpass
from hmac import compare_digest as compare_hash

def login():
    username = input('Python login: ')
    cryptedpasswd = pwd.getpwnam(username)[1]
    if cryptedpasswd:
        if cryptedpasswd == 'x' or cryptedpasswd == '*':
            raise ValueError('no support for shadow passwords')
        cleartext = getpass.getpass()
        return compare_hash(crypt.crypt(cleartext, cryptedpasswd), cryptedpasswd)
    else:
        return True

要使用最强的可用方法生成密码的哈希值,并对照原始值进行检查:

import crypt
from hmac import compare_digest as compare_hash

hashed = crypt.crypt(plaintext)
if not compare_hash(hashed, crypt.crypt(plaintext, hashed)):
    raise ValueError("hashed version doesn't validate against original")
首页