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+OpenCV感兴趣区域ROI提取方法

方法一:使用轮廓 步骤1 """src为原图""" ROI = np.zeros(src.shape, np.uint8) #感兴趣区域ROI proimage = src.co...

python使用writerows写csv文件产生多余空行的处理方法

初次接触python,学艺不精,第一次实战写一个文本处理的小程序时便遇到了头疼的问题。 先看代码: 生成的.CSV文件每两行之间都会多出一行空格(如下图),具体原因可参看点击打开链接...

详解Python字典小结

字典(dict)结构是Python中常用的数据结构,笔者结合自己的实际使用经验,对字典方面的相关知识做个小结,希望能对读者一些启发~ 创建字典 常见的字典创建方法就是先建立一个空字典,...

python中字符串数组逆序排列方法总结

python中字符串数组如何逆序排列?下面给大家介绍几种方法: 1、数组倒序: 原始元素的倒序排列 (1)切片 >>> arr = [1,2,3,4,3,4]>...

python获得图片base64编码示例

  复制代码 代码如下: #!/usr/bin/env python # -*- coding: utf-8 -*- import os, base64 icon = open...