Python生成MD5值的两种方法实例分析

yipeiwu_com6年前Python基础

本文实例讲述了Python生成MD5值的两种方法。分享给大家供大家参考,具体如下:

# -*- coding:utf-8 -*-
import datetime
# NO.1 使用MD5
import md5
src = 'this is a md5 test.'
m1 = md5.new()
m1.update(src)
print m1.hexdigest()

运行结果:

174b086fc6358db6154bd951a8947837

# -*- coding:utf-8 -*-
# NO.2 使用hashlib
import hashlib
src = 'this is a md5 test.'
m2 = hashlib.md5()
m2.update(src)
print m2.hexdigest()

运行结果:

174b086fc6358db6154bd951a8947837

对于同一个字符串而言,使用MD5和使用hashlib生成的MD5值是一样的

以下是使用file+时间戳生成一个唯一的MD5值

# -*- coding:utf-8 -*-
import md5
import time
now = 'file'+str(time.time())
print now,type(now)
m0 = md5.new()
m0.update(now)
print m0.hexdigest()

运行结果:

file1556241051.38 <type 'str'>
efdc1e1d6bbe949afb2cd0250d0244d2

############### 封装成函数 ###############################
# -*- coding:utf-8 -*-
import time
import hashlib
src = 'file'+str(time.time())
print src,type(src)
m2 = hashlib.md5()
m2.update(src)
file_id = m2.hexdigest()
print file_id,type(file_id)
def make_file_id(src):
  m1 = hashlib.md5()
  m1.update(src)
  return m1.hexdigest()
src = 'filed_46546546464631361sdfsdfgsdgfsdgdsgfsd'+str(time.time())
print make_file_id(src)

运行结果:

file1556241114.08 <type 'str'>
4d826f2298853d5f5ae209d6bf754b62 <type 'str'>
e6c5ad9dd0fa4f3d141f94b7c990710e

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程序设计有所帮助。

相关文章

打印出python 当前全局变量和入口参数的所有属性

def cndebug(obj=False): """ Author : Nemon Update : 2009.7.1 TO use : cndebug(obj) or cndebug...

Python 修改列表中的元素方法

Python 修改列表中的元素方法

如下所示: #打印列表文件 def show_magicians(magics) : for magic in magics : print(magic) #修改列表文件...

PyCharm-错误-找不到指定文件python.exe的解决方法

PyCharm-错误-找不到指定文件python.exe的解决方法

1、现象 系统提示找不到指定的文件: Error running 'hello': Cannot run program "B:\pystudy\venv\Scripts\python....

Python利用Beautiful Soup模块修改内容方法示例

前言 其实Beautiful Soup 模块除了能够搜索和导航之外,还能够修改 HTML/XML 文档的内容。这就意味着能够添加或删除标签、修改标签名称、改变标签属性值和修改文本内容等等...

Python ftp上传文件

以下代码比较简单,对python实现ftp上传文件相关知识感兴趣的朋友可以参考下 #encoding=utf8 from ftplib import FTP #加载ftp模块 IP...