用python计算md5,sha1,cr
原文:Http://blog.csdn.net/marshall001/article/details/50097705
为了确保从网上下载的文件或程序完整并且没有被篡改,一般官网上都会给出文件的md5或sha1。我们拿到一个软件,第一步应当是校验这个值与官网给的是否一致,如果不一致的话就赶紧删掉吧。
在Mac上计算一个文件的md5, sha1, crc32:
命令 | 输出 |
---|---|
$ md5 shark.jpg | MD5 (shark.jpg) = 61aead6a48da0fb25618333590745aa7 |
$ shasum shark.jpg | acfe8421e3ad39cf73f19cef02aa3e692e25d5a2 shark.jpg |
$ crc32 shark.jpg | adc64e03 |
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)))
- 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
- 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
$ Python3 test.py shark.jpg
,输出:
md5: 61aead6a48da0fb25618333590745aa7
sha1: acfe8421e3ad39cf73f19cef02aa3e692e25d5a2
crc32: adc64e03
- 1
- 2
- 3
- 1
- 2
- 3
与mac上的计算一致。
相关文章