0%

Hash校验

前言

一个简单的校验文件哈希值的小工具


源码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
# -*- coding: utf-8 -*-
# File : check_hash.py
# Author : MeteorDream
# Time : 2022/07/24 14:00:08
# language: Python
# Software: Visual Studio Code


"""
计算文件哈希值, 如果给出了文件哈希值,会校验哈希值是否匹配
"""

import argparse
import hashlib
import os

class ProgressBar:
""" 进度条 """
MAX_LENGTH = 25 # length of progress bar
STYLE_UNDO = '*' # show style of undo
STYLE_DONE = '=' # show syle of finish
def __init__(self, total=100, prefix="Loop"):
self.cur = 0
self.total = total
self.prefix = prefix

def restart(self, cur=None, total=None):
if cur is not None:
assert isinstance(cur, int), "Error type for cur: {}".format(cur)
self.cur = cur
if total is not None:
assert isinstance(total, int), "Error type for total: {}".format(total)
self.total = total

def step(self, val=1):
if self.cur >= self.total: return
self.cur += val
undo = int(self.MAX_LENGTH * min(self.cur / self.total, 1))
print("{} [{}{}{}] {:>5.2f}%".format(self.prefix, self.STYLE_DONE * (max(1, undo) - 1), '>', self.STYLE_UNDO * (self.MAX_LENGTH - undo), self.cur / self.total * 100), end='\r')

if __name__ == '__main__':
parser = argparse.ArgumentParser(description="To check hash value for file")
parser.add_argument("-f", "--filename", nargs='+', default=[], type=str, help='File name (default: all file in current path)')
parser.add_argument("-v", "--hash", nargs='+', default=None, type=str, help='Hash value for file')
parser.add_argument("-alg", "--algorithm", default='md5', choices=hashlib.algorithms_available, type=str, help="Hash algorithm")
args = parser.parse_args()

filelist = args.filename
if not filelist:
filelist = list(filter(os.path.isfile, os.listdir()))

hashlist = args.hash
if hashlist is None:
hashlist = [None for _ in filelist]
assert len(hashlist) == len(filelist), "Unmatch l file number({}) and hash val number{}".format(len(hashlist), len(filelist))

alg = args.algorithm
for filename, hashval in zip(filelist, hashlist):
if alg == 'md5':
hashobj = hashlib.md5()
elif alg == 'sha256':
hashobj = hashlib.sha256()
else:
hashobj = hashlib.new(args.algorithm)
pb = ProgressBar(total=os.stat(filename).st_size, prefix=filename)
with open(filename, 'rb') as f:
for line in f:
hashobj.update(line)
pb.step(len(line))
print(" " * 100, end='\r')
out = hashobj.hexdigest()
if hashval is None:
print("{} value of {} is {}".format(alg, filename, out))
else:
if out == hashval:
print("{} value of {} is match ({})".format(alg, filename, out))
else:
print("ERROR: {} value of {} is not match (true value: {})".format(alg, filename, out))

input("\nFinish!\n")

使用方法

文件结构如下

1
2
3
4
──┬ check_hash.py
├ example.txt
├ example2.exe
┕ example3.png

使用 python check_bash.py -h 可查看帮助信息

计算文件哈希值

通过以下命令即可计算, 文件名空格隔空

1
python check_hash.py -f example.txt example2.exe

如果不带参数会计算当前目录下所有文件的哈希校验值

1
2
3
md5 value of example.txt is a64443762e18c2a8e253eaef9acf9798
md5 value of example2.exe is fc221a15971d143397eebefba7c1612a
md5 value of example3.png is e4179d2ed02e5e65d942f31dbdccbc34

校验哈希值

为了避免手工对比校验值的麻烦,可以手动传入文件的校验值,计算后会自动比对结果是否一致

1
python check_hash.py -f example.txt example2.exe -v a64443762e18c2a8e253eaef9acf9798 fc221a15971d143397eebefba7c16120

输出结果

1
2
md5 value of example.txt is match (a64443762e18c2a8e253eaef9acf9798)
ERROR: md5 value of example2.exe is not match (true value: fc221a15971d143397eebefba7c1612a)

其他哈希校验值

可以传入 -alg 参数计算其他哈希校验值或校验,可选值可以通过 -h 查看

1
2
3
> python check_hash.py -h
usage: check_hash.py [-h] [-f FILENAME [FILENAME ...]] [-v HASH [HASH ...]]
[-alg {sha256,mdc2,shake_128,sha3_384,sha512_256,sha512,whirlpool,md4,sha1,sha3_256,blake2s,md5-sha1,sm3,sha3_512,shake_256,sha384,blake2b,sha512_224,sha3_224,md5,sha224,ripemd160}]

可见在我的计算机上可用的值为 sha256,mdc2,shake_128,sha3_384,sha512_256,sha512,whirlpool,md4,sha1,sha3_256,blake2s,md5-sha1,sm3,sha3_512,shake_256,sha384,blake2b,sha512_224,sha3_224,md5,sha224,ripemd160

如果想计算 sha256, 则

1
python check_hash.py -alg sha256

输出结果为:

1
2
3
4
sha256 value of check_hash.exe is 4af8c6f685d09ba54b67aabf94a094bc46e6eae7a14f4f9b01f4496425059e7d
sha256 value of example.txt is 1432916e05d050bcfc8ed91f5cbf2470f74e00ae3d364c61a481e0230df8f576
sha256 value of example2.exe is 4af8c6f685d09ba54b67aabf94a094bc46e6eae7a14f4f9b01f4496425059e7d
sha256 value of example3.png is 3bf89007fd48465b399b2edd78878b257b8fcc8d9fd350a3b5f5c5557dab76a7

也可以指定文件或指定哈希值进行校验,这里不再赘述

--- ♥ end ♥ ---

欢迎关注我呀~