zl程序教程

您现在的位置是:首页 >  后端

当前栏目

python计算二进制bin文件hash值

2023-09-11 14:17:11 时间

一 hash的价值

  hash值的唯一性仅仅在是同一个文件的情况下得到了同样的hash值,而哪怕错误一个字节也会得到不一样的hash值。

 hash值得最大价值就是唯一性。这样在bin文件检查和校验这块用处非常大,做嵌入式的,经常会遇到版本无法找到情况,利用hash来查找bin文件是否一致,非常方便。

 

二 实例分析

 

  python以简洁著称,下面给出一个python的例子:

 

import os
import argparse
import hashlib

def check_file_hash(bin_file):
    f = open(bin_file,"rb")
    thehash = hashlib.md5()
    theline = f.readline()

    while(theline):
        thehash.update(theline)
        theline = f.readline()

    return thehash.hexdigest()


def get_parser():
    parser = argparse.ArgumentParser(description='change extension of files in a working directory')
    parser.add_argument('bin_file', metavar='BIN_FILE', type=str, nargs=1,
                        help='the directory where to change extension')
    return parser

def main():
    parser = get_parser()
    args = vars(parser.parse_args())

    bin_file = args['bin_file'][0]

    hash_value = check_file_hash(bin_file)
    print("hash_value",hash_value)

if __name__=='__main__':
    main()

 

  github路径:

https://github.com/DyLanCao/python_cabin.git

 

三 总结

 能让计算机做的,尽量使用计算机。