hashlib主要提供字符加密功能,将md5和sha模块整合到了一起,支持md5,sha1, sha224, sha256, sha384, sha512等算法。

在学习hashlib模块之前,先来看看py2.x与py3.x对于这个模块的说明。

py2.x
hashlib module
new(name, string='') - returns a new hash object implementing the   #返回值为一个hash对象
                       given hash function; initializing the hash
                       using the given string data.

Named constructor functions are also available, these are much faster
than using new():

md5(), sha1(), sha224(), sha256(), sha384(), and sha512()  #python2.x提供的加密算法

More algorithms may be available on your platform but the above are
guaranteed to exist.

NOTE: If you want the adler32 or crc32 hash functions they are available in
the zlib module. #如果想使用adler32和crc32,就导入zlib库

Choose your hash function wisely.  Some have known collision weaknesses.
sha384 and sha512 will be slow on 32 bit platforms.#sha384和sha512在32位平台效率很低

Hash objects have these methods:
 - update(arg): Update the hash object with the string arg.
 - digest():    Return the digest of the strings passed to the update() method
                so far. This may contain non-ASCII characters, including
                NUL bytes.
 - hexdigest(): Like digest() except the digest is returned as a string of
                double length, containing only hexadecimal digits.
 - copy():      Return a copy (clone) of the hash object. This can be used to
                efficiently compute the digests of strings that share a common
                initial substring.
hashlib module - A common interface to many hash functions.

new(name, data=b'', **kwargs) - returns a new hash object implementing the
                                given hash function; initializing the hash
                                using the given binary data.

Named constructor functions are also available, these are faster
than using new(name):

md5(), sha1(), sha224(), sha256(), sha384(), sha512(), blake2b(), blake2s(),
sha3_224, sha3_256, sha3_384, sha3_512, shake_128, and shake_256.

More algorithms may be available on your platform but the above are guaranteed
to exist.  See the algorithms_guaranteed and algorithms_available attributes
to find out what algorithm names can be passed to new().

NOTE: If you want the adler32 or crc32 hash functions they are available in
the zlib module.

Choose your hash function wisely.  Some have known collision weaknesses.
sha384 and sha512 will be slow on 32 bit platforms.

Hash objects have these methods:
 - update(arg): Update the hash object with the bytes in arg. Repeated calls
                are equivalent to a single call with the concatenation of all
                the arguments.
 - digest():    Return the digest of the bytes passed to the update() method
                so far.
 - hexdigest(): Like digest() except the digest is returned as a unicode
                object of double length, containing only hexadecimal digits.
 - copy():      Return a copy (clone) of the hash object. This can be used to
                efficiently compute the digests of strings that share a common
                initial substring.

从上面的表述我们可以看出,在py2.x环境下,如果要加密一个字符串可以按照如下格式:

>>> import hashlib
>>> m = hashlib.md5()
>>> m.update("Nobody inspects")#主意这里和py3.x不同
>>> m.update(" the spammish repetition")
>>> m.digest()
 '\\xbbd\\x9c\\x83\\xdd\\x1e\\xa5\\xc9\\xd9\\xde\\xc9\\xa1\\x8d\\xf0\\xff\\xe9'

 >> hashlib.sha224("Nobody inspects the spammish repetition").hexdigest()
  'a4337bc45a8fc544c03f52dc550cd6e1e87021bc896588bd79e901e2'

 在py3.x环境下,如果要加密一个字符串可以按照如下格式:

>>> import hashlib
>>> m = hashlib.md5()
>>> m.update(b"Nobody inspects")
>>> m.update(b" the spammish repetition")
>>> m.digest()
    b'\\xbbd\\x9c\\x83\\xdd\\x1e\\xa5\\xc9\\xd9\\xde\\xc9\\xa1\\x8d\\xf0\\xff\\xe9'

>>> hashlib.sha224(b"Nobody inspects the spammish repetition").hexdigest()

  'a4337bc45a8fc544c03f52dc550cd6e1e87021bc896588bd79e901e2'

1.模块提供的常数

hash.digest_size
The size of the resulting hash in bytes.#返回hash结果的字节数

hash.block_size
The internal block size of the hash algorithm in bytes.#返回hash算法内部块的字节数

2.hash对象拥有的方法

hash.update(arg)
Update the hash object with the string arg. 
#m.update(a);
#m.update(b)
#上面两步等价于m.update(a+b).也就是对于同一字符串用不同值加密,就等价于用这两种加密字符之和再加密 hash.digest() Return the digest of the strings passed to the update() method so far. This is a string of digest_size bytes which may contain non-ASCII characters, including null bytes. hash.hexdigest() Like digest() except the digest is returned as a string of double length, containing only hexadecimal digits. This may be used to exchange the value safely in email or other non-binary environments. hash.copy() Return a copy (“clone”) of the hash object. This can be used to efficiently compute the digests of strings that share a common initial substring.

 以上四种方法,在py2.x和py3.x没有差别,只不过在传入参数有点区别。

3.例子

#####py2.7,以下两种方式没区别##########
import hashlib
string = 'chenwei'
md5 = hashlib.md5()  # 获得一个md5对象
print md5
md5.update(string)  # 用string来更新上面获得的md5对象
res = md5.hexdigest()  # 输出加密后的字符
print "md5加密的结果为:",res

md5 = hashlib.md5()  # 获得一个md5对象
print md5
md5.update('chenwei')  # 用string来更新上面获得的md5对象
res = md5.hexdigest()  # 输出加密后的字符
print "md5加密的结果为:",res

#####以下编译环境py3.6,注意看两种方式区别####
import hashlib
string = 'chenwei'
md5 = hashlib.md5()  # 获得一个md5对象
print(md5)
md5.update(string.encode("utf-8"))  # 用string来更新上面获得的md5对象
res = md5.hexdigest()  # 输出加密后的字符
print("md5加密的结果为:", res)

import hashlib
md5 = hashlib.md5()  # 获得一个md5对象
print(md5)
md5.update(b'chenwei')  # 用string来更新上面获得的md5对象
res = md5.hexdigest()  # 输出加密后的字符
print("md5加密的结果为:", res)

 如果需要加密的字符串长度较长,可以分为两次加密,其加密效果与一次加密是一样的。看下面代码:

######py2.x代码,py3.x类型,这里就不写了######
md5 = hashlib.md5()
md5.update("how to use md5 in python hashlib?")
res = md5.hexdigest() #返回十六进制的hash值
res2 = md5.digest()  #返回二进制的hash值
print res,res2

md5 = hashlib.md5()
md5.update("how to use md5 in ")
md5.update("python hashlib?")
res = md5.hexdigest()  # 返回十六进制的hash值
res2 = md5.digest()   # 返回二进制的hash值
print res,res2

上面种情况是一样的。

  其他算法如:sha1(), sha224(), sha256(), sha384(), and sha512()与md5用法一样,就把上面的md5换成sha1....等等即可。

 4.应用

  任何允许用户登录的网站都会存储用户登录的用户名和口令。如果以明文保存用户口令,如果数据库泄露,所有用户的口令就落入黑客的手里。此外,网站运维人员是可以访问数据库的,也就是能获取到所有用户的口令。正确的保存口令的方式是不存储用户的明文口令,而是存储用户口令的摘要,比如MD5:当用户登录时,首先计算用户输入的明文口令的MD5,然后和数据库存储的MD5对比,如果一致,说明口令输入正确,如果不一致,口令肯定错误。

  实例:模拟登陆加密程序

#python3.6
import hashlib

def md5(arg):
    hash = hashlib.md5(bytes('Davve;.',encoding = 'utf-8'))
    hash.update(bytes(arg,encoding = 'utf-8'))
    return hash.hexdigest()

def register(user,pwd):
    with open("db",'a',encoding='utf-8') as f:
        tmp = user + '|' + md5(pwd)
        f.write(tmp)

def login(user,pwd):
    with open("db",'r',encoding='utf-8') as f:
        for line in f:
            u,p = line.strip().split("|")
            if u == user and p == md5(pwd):  #加密是一次性的,不能反解
                return True

i = input("1:登陆,2:注册\n")
':
    usr = input("用户名:")
    pwd = input("密码:")
    register(usr,pwd)
':
    usr = input("用户名:")
    pwd = input("密码:")
    r = login(usr,pwd)
    if r:
        print("登陆成功")
    else:
        print("登陆失败")

python标准库]Hashlib的更多相关文章

  1. python第六天 函数 python标准库实例大全

    今天学习第一模块的最后一课课程--函数: python的第一个函数: 1 def func1(): 2 print('第一个函数') 3 return 0 4 func1() 1 同时返回多种类型时, ...

  2. 转--Python标准库之一句话概括

    作者原文链接 想掌握Python标准库,读它的官方文档很重要.本文并非此文档的复制版,而是对每一个库的一句话概括以及它的主要函数,由此用什么库心里就会有数了. 文本处理 string: 提供了字符集: ...

  3. Python 标准库一览(Python进阶学习)

    转自:http://blog.csdn.net/jurbo/article/details/52334345 写这个的起因是,还是因为在做Python challenge的时候,有的时候想解决问题,连 ...

  4. python 标准库大全

    python 标准库 文本 string:通用字符串操作 re:正则表达式操作 difflib:差异计算工具 textwrap:文本填充 unicodedata:Unicode字符数据库 string ...

  5. Python标准库14 数据库 (sqlite3)

    作者:Vamei 出处:http://www.cnblogs.com/vamei 欢迎转载,也请保留这段声明.谢谢! Python自带一个轻量级的关系型数据库SQLite.这一数据库使用SQL语言.S ...

  6. python标准库00 学习准备

    Python标准库----走马观花 python有一套很有用的标准库.标准库会随着python解释器一起安装在你的电脑上的.它是python的一个组成部分.这些标准库是python为你准备的利器,可以 ...

  7. Python标准库:内置函数hasattr(object, name)

    Python标准库:内置函数hasattr(object, name) 本函数是用来判断对象object的属性(name表示)是否存在.如果属性(name表示)存在,则返回True,否则返回False ...

  8. python标准库xml.etree.ElementTree的bug

    使用python生成或者解析xml的方法用的最多的可能就数python标准库xml.etree.ElementTree和lxml了,在某些环境下使用xml.etree.ElementTree更方便一些 ...

  9. 【python】Python标准库defaultdict模块

    来源:http://www.ynpxrz.com/n1031711c2023.aspx Python标准库中collections对集合类型的数据结构进行了很多拓展操作,这些操作在我们使用集合的时候会 ...

随机推荐

  1. spring mvc中,直接注入的HttpServletRequst是否安全呢?

    看似很简单的一个问题,借此追踪下spring的源码处理 在写springMVC的Control中有很多这种代码, 如需要获取request对象去做某些事情 如: @Controller @Reques ...

  2. 一行code实现ADO.NET查询结果映射至实体对象。

    AutoMapper是一个.NET的对象映射工具. 主要用途 领域对象与DTO之间的转换.数据库查询结果映射至实体对象. 这次我们说说 数据库查询结果映射至实体对象. 先贴一段代码: public S ...

  3. BogoMIPS与calibrate_delay

    在分析Arm+linux启动信息的时候.发现有一个信息竟然耗费了2s的时间,这简直是不能忍受的.这个耗时大鳄是什么东西哪,请看分析信息: [    0.000000] console [ttyMT0] ...

  4. BZOJ 1266: [AHOI2006]上学路线route

    题目描述 可可和卡卡家住合肥市的东郊,每天上学他们都要转车多次才能到达市区西端的学校.直到有一天他们两人参加了学校的信息学奥林匹克竞赛小组才发现每天上学的乘车路线不一定是最优的. 可可:"很 ...

  5. 跨域问题解决方案(HttpClient安全跨域 & jsonp跨域)

    1 错误场景 今天要把项目部署到外网的时候,出现了这样的问题, 我把两个项目放到自己本机的tomcat下, 进行代码调试, 运行 都没有问题的, 一旦把我需要调用接口的项目B放到其他的服务器上, 就会 ...

  6. hive集成sentry

    1.安装配置sentry 详细步骤见上一篇安装配置sentry 2.配置hive 2.1 Hive-server2集成Sentry 在 /etc/hive/conf/hive-site.xml中添加: ...

  7. IOS开发常见错误

    . 问题表现:什么情况?方法居然无法拉线? 问题简述:ios的空间拉线到一个.h .m文件中 居然多次拖动无效.. 问题解决:ios的空间响应单单在代码中创建一个方法是没用的,这个时候通常跟空间是没有 ...

  8. Scrapy 爬虫框架入门案例详解

    欢迎大家关注腾讯云技术社区-博客园官方主页,我们将持续在博客园为大家推荐技术精品文章哦~ 作者:崔庆才 Scrapy入门 本篇会通过介绍一个简单的项目,走一遍Scrapy抓取流程,通过这个过程,可以对 ...

  9. UI-UIwindow

    1.什么是UI? UI  (User Interface) : 用户界面,用户看到的各种各样的页面元素: 2.什么是UIWindow ? UIWindow : 一个基础容器,往窗口上放不同的东西,每个 ...

  10. @PathVariable和@RequestParam的区别,@SessionAttributes

    简介: handler method参数绑定常用的注解,我们根据他们处理的Request的不同内容部分分为四类: A:处理requet uri部分(这里指uri template中variable,不 ...