gpt4 book ai didi

python - 对所有字符串获取相同的 sha1 哈希值

转载 作者:行者123 更新时间:2023-12-01 04:59:20 24 4
gpt4 key购买 nike

我有一个打开文件的脚本,查找包含 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()函数传递匹配对象,并使用其返回值作为替换。现在您可以计算第二组的哈希值!

演示:

>>> 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< .

关于python - 对所有字符串获取相同的 sha1 哈希值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26632739/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com