0

我试图在定义的字符集中加密所有可能的字符串,然后将它们与用户输入给出的哈希值进行比较。

这是我目前拥有的

import string
from itertools import product
import crypt

def decrypt():
    hash1 = input("Please enter the hash: ")
    salt = input("Please enter the salt: ")
    charSet = string.ascii_letters + string.digits
    for wordchars in product(charSet, repeat=2):
        hash2 = crypt.METHOD_CRYPT((wordchars), (salt))
        print (hash2)

显然它还没有完成,但我在加密“wordchars”时遇到了麻烦

任何帮助表示赞赏

4

4 回答 4

0

crypt.METHOD_CRYPT不可调用,因此您提供的回溯与您问题中的代码不对应。crypt.METHOD_CRYPT可以用作crypt.crypt()function的第二个参数。

同样正如@martineau指出的那样,wordchars它是一个元组,但您需要一个字符串才能传递给crypt.crypt()函数。

文档

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

要从给定加密形式的已定义字符集中查找纯文本:salt plus hash,您可以:

from crypt import crypt
from itertools import product
from string import ascii_letters, digits

def decrypt(crypted, charset=ascii_letters + digits):
    # find hash for all 4-char strings from the charset
    # and compare with the given hash
    for candidate in map(''.join, product(charset, repeat=4)):
        if crypted == crypt(candidate, crypted):
            return candidate

例子

salt, hashed = 'qb', '1Y.qWr.DHs6'
print(decrypt(salt + hashed))
# -> e2e4
assert crypt('e2e4', 'qb') == (salt + hashed)

断言行确保crypt使用单词e2e4和盐调用qb会产生盐qb1Y.qWr.DHs6在哪里qb

于 2012-11-16T02:09:21.890 回答
0

嗯可能更好地使用bcrypt? https://github.com/fwenzel/python-bcrypt

于 2012-11-15T16:51:06.723 回答
0

这是我完全不同的答案,基于 JF Sebastian 的回答和对我之前回答的评论。最重要的一点是它crypt.METHOD_CRYPT不是可调用的,即使文档有点混淆地调用散列方法,就好像它是模块或实例的方法函数一样。crypt它不是 - 只是将其视为模块支持的各种加密之一的 id 或名称。

所以你的代码的问题是双重的:一个是你试图wordchars用作一个字符串,而它实际上是一个由生成的元组product(),第二个是你试图调用 id crypt.METHOD_CRYPT

我在回答这个问题时有点不利,因为我没有运行 Unix,没有安装 Python v3.3,也没有完全理解你想要用你的代码完成什么。鉴于所有这些警告,我认为从您的代码派生的类似以下内容至少应该运行:

import string
from itertools import product
import crypt

def decrypt():
    hash1 = input("Please enter the hash: ")
    salt = input("Please enter the salt: ")
    charSet = string.ascii_letters + string.digits
    for wordchars in product(charSet, repeat=2):
        hash2 = crypt.crypt(''.join(wordchars), salt=salt)  # or salt=crypt.METHOD_CRYPT
        print(hash2)
于 2012-11-15T18:54:49.407 回答
0

下面是一个简单的程序,可以满足您的要求:

def gen_word(charset, L):
    if L == 1: 
        for char in charset:
            yield char
        raise StopIteration
    for char in charset:
        for word in gen_word(charset, L - 1):
            yield char + word


def encrypt(word):
    '''Your encrypt function, replace with what you wish'''
    return word[::-1]


charset = ['1', '2', '3']


user_word = '12'
user_hash = encrypt(user_word)
max_length = 3


for length in range(1, max_length):
    for word in gen_word(charset, length):
        if encrypt(word) == user_hash:
            print 'Word found: %s' % word

基本上,它使用 python 生成器从固定长度的字符集中生成单词。您可以用您想要的任何内容替换 encrypt 函数(在示例中是用作哈希的字符串反转)。

请注意,使用实际的现代散列方法,解密普通密码需要很长时间,所以我认为你不能真正使用它。

于 2012-11-15T17:18:35.157 回答