用python计算md5,sha1,crc32

时间:2021-12-20 05:00:39

Linux下计算md5sum,sha1sum,crc:

命令          输出

$md5sum hello    f19dd746bc6ab0f0155808c388be8ff0  hello

$sha1sum hello    79e560a607e3e6e9be2c09a06b7d5062cb5ed566  hello

$crc32 hello      327213a2

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

#test.py
#!/usr/bin/env python

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

$python test.py hello

结果:

md5: f19dd746bc6ab0f0155808c388be8ff0
sha1: 79e560a607e3e6e9be2c09a06b7d5062cb5ed566
crc32: 327213a2