用python计算md5,sha1,crc32

吕志诚
2023-12-01

为了确保从网上下载的文件或程序完整并且没有被篡改,一般官网上都会给出文件的md5或sha1。我们拿到一个软件,第一步应当是校验这个值与官网给的是否一致,如果不一致的话就赶紧删掉吧。

在Mac上计算一个文件的md5, sha1, crc32:

命令输出
$ md5 shark.jpgMD5 (shark.jpg) = 61aead6a48da0fb25618333590745aa7
$ shasum shark.jpgacfe8421e3ad39cf73f19cef02aa3e692e25d5a2 shark.jpg
$ crc32 shark.jpgadc64e03

python也能做这个工作,其中md5和sha1需import hashlib, crc32可以import zlib

#!/usr/bin/env python3

from hashlib import md5, sha1
from zlib import crc32
import sys

def getMd5(filename): #计算md5
    mdfive = md5()
    with open(filename, 'rb') as f:
        mdfive.update(f.read())
    return mdfive.hexdigest()

def getSha1(filename): #计算sha1
    sha1Obj = sha1()
    with open(filename, 'rb') as f:
        sha1Obj.update(f.read())
    return sha1Obj.hexdigest()

def getCrc32(filename): #计算crc32
    with open(filename, 'rb') as f:
        return crc32(f.read())

if len(sys.argv) < 2:
    print('You must enter the file')
    exit(1)
elif len(sys.argv) > 2:
    print('Only one file is permitted')
    exit(1)

filename = sys.argv[1]

print('{:8} {}'.format('md5:', getMd5(filename)))
print('{:8} {}'.format('sha1:', getSha1(filename)))
print('{:8} {:x}'.format('crc32:', getCrc32(filename)))

$ python3 test.py shark.jpg,输出:

md5:     61aead6a48da0fb25618333590745aa7
sha1:    acfe8421e3ad39cf73f19cef02aa3e692e25d5a2
crc32:   adc64e03

与mac上的计算一致。

 类似资料: