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

柳树舒展开了黄绿嫩叶的枝条,在微微的春风中轻柔地拂动,就像一群群身着绿装的仙女在翩翩起舞。夹在柳树中间的桃树也开出了鲜艳的花朵,绿的柳,红的花,真是美极了!

本文实例讲述了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.haodaima.com/password/txt_encode

MD5在线加密工具:
http://tools.haodaima.com/password/CreateMD5Password

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

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

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

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

本文Python生成MD5值的两种方法实例分析到此结束。你关注什么样的人,决定你将看到什么样的世界。小编再次感谢大家对我们的支持!

您可能有感兴趣的文章
Python自动化运维-使用Python脚本监控华为AR路由器关键路由变化

Python自动化运维-netmiko模块设备自动发现

Python自动化运维—netmiko模块连接并配置华为交换机

Python自动化运维-利用Python-netmiko模块备份设备配置

Python3内置模块之json编码解码方法详解