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

yipeiwu_com6年前Python基础

本文实例讲述了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相关内容感兴趣的读者可查看本站专题:《Python加密解密算法与技巧总结》、《Python编码操作技巧总结》、《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》及《Python入门与进阶经典教程

希望本文所述对大家Python程序设计有所帮助。

相关文章

Python yield与实现方法代码分析

yield的功能类似于return,但是不同之处在于它返回的是生成器。 生成器 生成器是通过一个或多个yield表达式构成的函数,每一个生成器都是一个迭代器(但是迭代器不一定是生成器)...

Python按行读取文件的简单实现方法

1:readline() file = open("sample.txt") while 1: line = file.readline() if not line:...

windows下pycharm安装、创建文件、配置默认模板

windows下pycharm安装、创建文件、配置默认模板

本文为大家分享了windows下pycharm安装、创建文件、配置默认模板的具体步骤,供大家参考,具体内容如下 步骤: 下包 —->安装——>创建文件—->定制模板...

python使用原始套接字发送二层包(链路层帧)的方法

发送端代码: #!/usr/bin/python # -*- coding: UTF-8 -*- import socket import struct raw_socket =...

Python 使用with上下文实现计时功能

引言 with 语句是从 Python 2.5 开始引入的一种与异常处理相关的功能(2.5 版本中要通过 from __future__ import with_statement 导...