本文实例讲述了Python实现计算文件MD5和SHA1的方法。分享给大家供大家参考,具体如下:
不多说,直接源码:
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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
|
#file md5
import sys;
import hashlib;
import os.path;
def GetFileMd5(strFile):
file = None ;
bRet = False ;
strMd5 = "";
strSha1 = "";
try :
file = open (strFile, "rb" );
md5 = hashlib.md5();
sha1 = hashlib.sha1();
strRead = "";
while True :
strRead = file .read( 8096 );
if not strRead:
break ;
else :
md5.update(strRead);
sha1.update(strRead);
#read file finish
bRet = True ;
strMd5 = md5.hexdigest();
strSha1 = sha1.hexdigest();
except :
bRet = False ;
finally :
if file :
file .close()
return [bRet, strMd5, strSha1];
def writFile(strInfo):
file = None ;
file = open ( "E:\\1.txt" , 'w+' );
file .write(strInfo);
file .write( "\n" );
if file :
file .close();
if "__main__" = = __name__:
bOK , md5str1, sha1str1 = GetFileMd5( "E:\\1.mp3" );
print (md5str1);
md5All = md5str1 + "\t" + sha1str1;
md5All + = "\n" ;
bOK , md5str2, sha1str2 = GetFileMd5( "E:\\2.mp3" );
print (md5str2);
writFile(md5str2 + "\t" + sha1str2);
md5All + = (md5str2 + "\t" + sha1str2);
md5All + = "\n" ;
bOK , md5str3, sha1str3 = GetFileMd5( "E:\\3.mp3" );
print (md5str3);
writFile(md5str3 + "\t" + sha1str3);
md5All + = (md5str2 + "\t" + sha1str3);
md5All + = "\n" ;
writFile(md5All);
|
产生的文件如下:
e712ca35354ff51803b51f3c7db03a81 8417609d07ce1bbd53111f1664ecfb63422749bb
34d7451ef9fbeb4c1ebbf2ed5cb96329 9d7009e1f1cd750f5a795d25491a5d294a45f3b2
34d7451ef9fbeb4c1ebbf2ed5cb96329 8a11f608aee135dd1d4b8c64af0721790e0a0b32
要是自己使用,改吧,改吧就可以使用了。
PS:关于加密解密感兴趣的朋友还可以参考本站在线工具:
文字在线加密解密工具(包含AES、DES、RC4等):https://tool.zzvips.com/t/txtencode/
MD5在线加密工具:https://tool.zzvips.com/t/md5/
在线sha1/sha224/sha256/sha384/sha512加密工具:https://tool.zzvips.com/t/sha/
希望本文所述对大家Python程序设计有所帮助。
原文链接:https://blog.csdn.net/qyee16/article/details/50086603