如何在Python中对字符串进行哈希处理?

3

我有一个代码,它可以从给定的字符列表输出所有可能的组合,如下所示:

def charList():
    charSet = string.ascii_letters + string.digits
    for wordchars in product(charSet, repeat=8):
        print(''.join(wordchars))

现在我需要将输出字符串转换成DES哈希值,然后将输出与用户输入进行比较,以查看是否找到任何匹配项。

我已经做了一些研究,并没有取得太多进展。所以想知道这里是否有人可以提供帮助?


5
DES是一种分块密码,而不是哈希函数。换句话说,你不能使用DES来对数据进行哈希处理,而是需要使用它来进行加密。虽然有从分组密码构建哈希函数的方法,但你需要明确指定你所指的哪种方法(我怀疑这并不是你最初想表达的意思)。 - user395760
3个回答

2

如果您想对字符串进行哈希(而不是加密),可以使用内置的hashlib模块:

>>> import hashlib
>>> m = hashlib.md5()
>>> m.update("Nobody inspects")
>>> m.update(" the spammish repetition")
>>> m.digest()
'\xbbd\x9c\x83\xdd\x1e\xa5\xc9\xd9\xde\xc9\xa1\x8d\xf0\xff\xe9'

编辑:如评论所述,现在更推荐使用 hashlib.sha256(),它的安全性更高。


尽管在当今这个时代,MD5已经是一个相当糟糕的选择,除了用于校验和(即使在那里,SHA-*也越来越受欢迎)。 - user395760
好的,知道了,谢谢。你能详细解释一下吗? - Emmanuel
1
MD5的输出大小相对较小,存在许多攻击方式(而且可能会发现更多攻击方式)。根据您的用例、生成碰撞的价值以及攻击者的资源,这可能是一个严重的问题。例如,Flame恶意软件利用MD5碰撞滥用了Microsoft证书。再加上存在更好的密码哈希算法(例如SHA-2),这意味着我们可能不应该再使用MD5了。 - user395760

1

http://docs.python.org/2/library/crypt.html

Platforms: Unix

This module implements an interface to the crypt(3) routine, which is a one-way hash function based upon a modified DES algorithm; see the Unix man page for further details. Possible uses include allowing Python scripts to accept typed passwords from the user, or attempting to crack Unix passwords with a dictionary.

Notice that the behavior of this module depends on the actual implementation of the crypt(3) routine in the running system. Therefore, any extensions available on the current implementation will also be available on this module

crypt.crypt(word, salt)

word will usually be a user’s password as typed at a prompt or in a graphical interface. salt is usually a random two-character string which will be used to perturb the DES algorithm in one of 4096 ways. The characters in salt must be in the set [./a-zA-Z0-9]. Returns the hashed password as a string, which will be composed of characters from the same alphabet as the salt (the first two characters represent the salt itself).

Since a few crypt(3) extensions allow different values, with different sizes in the salt, it is recommended to use the full crypted password as salt when checking for a password.

A simple example illustrating typical use:

import crypt, getpass, pwd 
def login():
        username = raw_input('Python login:')
        cryptedpasswd = pwd.getpwnam(username)[1]
        if cryptedpasswd:
            if cryptedpasswd == 'x' or cryptedpasswd == '*':
                raise NotImplementedError(
                    "Sorry, currently no support for shadow passwords")
            cleartext = getpass.getpass()
            return crypt.crypt(cleartext, cryptedpasswd) == cryptedpasswd
        else:
            return 1


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接