天天看點

用python計算md5,sha1,crc32

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

轉載于:https://www.cnblogs.com/luolizhi/p/5591044.html