Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 使用所有字符串获取相同的sha1哈希_Python_Regex_Hash_Sha1 - Fatal编程技术网

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

Python 使用所有字符串获取相同的sha1哈希,python,regex,hash,sha1,Python,Regex,Hash,Sha1,我有一个脚本,可以打开一个文件,查找任何包含HASH(“”的内容,并将其替换为HASH() 整个脚本如下所示: 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' *

我有一个脚本,可以打开一个文件,查找任何包含
HASH(“”
的内容,并将其替换为
HASH()

整个脚本如下所示:

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散列变得完全相同,这对我来说没有意义。如果我没有写入散列,而是用
散列({}).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\u with_hash()
函数传递匹配对象,其返回值用作替换。现在您可以计算第二组的哈希

演示:

>>重新导入
>>>定义散列(字符串):
...     返回'HASHED:{}'。格式(字符串[::-1])
... 
>>>样本='''\
... 散列(“”)
... '''
>>>re.sub(r'HASH\([“\”)(.*?\1\),'HASH({})').format(_HASH(r'\2')),sample)
'散列(散列:2\\)\n'
>>>def将_替换为_散列(匹配):
…返回'HASH({}').format(_HASH(match.group(2)))
... 
>>>re.sub(r'HASH\([“\”)(.*?\1\)”,将\u替换为\u HASH,sample)

'HASH(HASH:>ffutsIt似乎您调用了
\u HASH(r'\2')
,它将始终返回相同的值。()我不知道它只是用一个值替换了占位符,如果它是替换字符串。非常棒的演示和解释!谢谢!只是巧合,抱歉:/
>>> 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'