簡體   English   中英

使用所有字符串獲取相同的sha1哈希

[英]Getting the same sha1 hash with all strings

我有一個腳本可以打開文件,查找具有HASH("<stuff>")任何內容,並將其替換為HASH(<sha1(stuff)>)

整個腳本是這樣的:

import sys
import re
import hashlib

def _hash(seq, trim_bits=64):
    assert trim_bits % 8 == 0
    temp = hashlib.sha1(seq).hexdigest()
    temp = int(temp, 16) & eval('0x{}'.format('F' * (trim_bits/4)))
    temp = hex(temp)
    return str(temp[2:]).replace('L', '')

if __name__ == '__main__':
    assert len(sys.argv) == 3
    in_file = sys.argv[1]
    out_file = sys.argv[2]
    with open(in_file, 'r') as f:
        lines = f.readlines()
        out_handle = open(out_file, 'w')
        for line in lines:
            new_line = re.sub(r'HASH\((["\'])(.*?)\1\)', 'HASH({})'.format(_hash(r'\2')), line)
            out_handle.write(new_line)
        out_handle.close()

但是,當我運行此命令時,所有的sha1哈希值都變得完全相同,這對我來說毫無意義。 如果不是寫哈希,而是用HASH({}).format(r'\\2')切換,它將用雙引號之間的字符序列替換它。 那么,為什么sha1哈希返回相同的字符串?

您正在計算字符串r'\\2'的哈希值; re模塊僅在將其用作替換字符串時才替換該占位符,但是您在這里沒有這樣做。

而是使用替換函數從匹配對象傳遞組:

def replace_with_hash(match):
    return 'HASH({})'.format(_hash(match.group(2)))

new_line = re.sub(r'HASH\((["\'])(.*?)\1\)', replace_with_hash, line)

replace_with_hash()函數傳遞給match對象,並將其返回值用作替換對象。 現在您可以計算第二組的哈希值了!

演示:

>>> import re
>>> def _hash(string):
...     return 'HASHED: {}'.format(string[::-1])
... 
>>> sample = '''\
... HASH("<stuff>")
... '''
>>> re.sub(r'HASH\((["\'])(.*?)\1\)', 'HASH({})'.format(_hash(r'\2')), sample)
'HASH(HASHED: 2\\)\n'
>>> def replace_with_hash(match):
...     return 'HASH({})'.format(_hash(match.group(2)))
... 
>>> re.sub(r'HASH\((["\'])(.*?)\1\)', replace_with_hash, sample)
'HASH(HASHED: >ffuts<)\n'

我的_hash()函數只是反轉輸入字符串以顯示會發生什么。

第一個re.sub()是您的版本; 注意它如何返回'2\\\\' ,所以r'\\2'相反! 我的版本將<stuff>整齊地哈希為>futts<

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM