在python usig sha256算法中散列csv文件

时间:2018-06-06 10:18:30

标签: python python-3.x function csv hashlib

我想对csv文件中的4numberic锁进行某种破解,并找出锁码。

我看到一个标题here,但这不是同一个问题。

在这个项目中,我必须只输入“hashlib”和“csv”。

该程序应该只是一个def任务。

import hashlib
import csv

def hash_password_hack(input_file_name, output_file_name):
    # all the task must be here

csv文件包含名称和hashlib-sha256代码,如:

jack,99b057c8e3461b97f8d6c461338cf664bc84706b9cc2812daaebf210ea1b9974
huge,85432a9890aa5071733459b423ab2aff9f085f56ddfdb26c8fae0c2a04dce84c

代码介于0000和9999之间。所需的输出是代码。

jack,5104
huge,9770

2 个答案:

答案 0 :(得分:0)

已知sha256哈希算法是不可逆的。这意味着没有直接的方法从哈希中找回原始字符串。

但是这里可能键的熵非常有限:只有10000个可能的值。在这种情况下,最好的方法是强力攻击:将每个哈希值与10000个可能的值进行比较。稍微优化可能是预先计算10000个哈希值,然后仅使用字符串比较。

的伪代码:

build a list for hashes of byte string from `b'0000'` to `b'9999'`
for each line of the input csv file
    search index of second field in list of hashes
    raise an error of print a warning message if not found
    use it to write into output csv

从中记住什么:

无论哈希算法的质量如何,当熵较差时,密码为周:从不使用值可以用于简单的词典攻击。

答案 1 :(得分:0)

由于您只有00009999范围内的可能组合,因此可以为所有可能的组合创建sha256哈希值。这些可以以与您给出的CSV文件中存在的格式相同的格式存储在字典中,即十六进制摘要。这是使用range()提供所有数字,然后.format()将数字转换为带前导零的字符串。然后可以将其编码为字节并传递给hashlib。

一旦创建了字典,就可以直接在字典中查找每个哈希以获得匹配组合。 Python的CSV库可用于帮助读取和写入CSV文件。读取时,会自动拆分该行并将每个条目作为列表返回。对于写入相反的操作,即你给它一个项目列表,它将用它们之间自动添加的逗号分隔符来编写它们。您还应为文件指定newline=''

import hashlib
import csv

def hash_password_hack(input_file_name, output_file_name):
    # Generate all possible combinations
    hash_lookup = {}

    for combination_int in range(10000):
        combination_str = '{:04}'.format(combination_int)
        m = hashlib.sha256(combination_str.encode('ascii'))
        hash_lookup[m.hexdigest()] = combination_str

    with open(input_file_name, newline='') as f_input, open(output_file_name, 'w', newline='') as f_output:
        csv_input = csv.reader(f_input)
        csv_output = csv.writer(f_output)

        for user, hash in csv_input:
            csv_output.writerow([user, hash_lookup[hash]])

hash_password_hack('input.csv', 'output.csv')