python

超轻量级php框架startmvc

Python实现计算文件MD5和SHA1的方法示例

更新时间:2020-07-05 17:36:02 作者:startmvc
本文实例讲述了Python实现计算文件MD5和SHA1的方法。分享给大家供大家参考,具体如下:不

本文实例讲述了Python实现计算文件MD5和SHA1的方法。分享给大家供大家参考,具体如下:

不多说,直接源码:


#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等): http://tools.jb51.net/password/txt_encode

MD5在线加密工具: http://tools.jb51.net/password/CreateMD5Password

在线散列/哈希算法加密工具: http://tools.jb51.net/password/hash_encrypt

在线MD5/hash/SHA-1/SHA-2/SHA-256/SHA-512/SHA-3/RIPEMD-160加密工具: http://tools.jb51.net/password/hash_md5_sha

在线sha1/sha224/sha256/sha384/sha512加密工具: http://tools.jb51.net/password/sha_encode

Python 计算 文件 MD5 SHA1