hashlib模块学习笔记

该模块实现了许多不同安全散列和消息摘要算法的通用接口。

概要

提供了以下那么多 信息摘要算法,本文不对算法过多讲解, 只是简单说一下,如何使用hashlib 模块提供的接口, 调用函数. 至于算法的实现这里没有涉及.

__always_supported = ('md5', 'sha1', 'sha224', 'sha256', 'sha384', 'sha512',
                      'blake2b', 'blake2s',                             
                      'sha3_224', 'sha3_256', 'sha3_384', 'sha3_512',
                      'shake_128', 'shake_256')                                                    
1. 来看一下demon
#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
"""
@author: Frank 
@contact: [email protected]
@file: haslib_test.py
@time: 2018/7/7 上午8:24

"""

# import

import hashlib


__always_supported = ('md5', 'sha1', 'sha224', 'sha256', 'sha384', 'sha512',
                      'blake2b', 'blake2s',
                      'sha3_224', 'sha3_256', 'sha3_384', 'sha3_512',
                      'shake_128', 'shake_256')                                                             


def md5_test():
    md5 = hashlib.md5()
    data = 'I am frank. hello everyone!'.encode('utf-8')
    md5.update(data)

    # 占用多少bytes
    print(md5.digest_size)

    # 返回二进制的加密结果
    print(md5.digest())
    # 返回十六进制的机密结果
    print(md5.hexdigest())


def sha256_test():
    sha = hashlib.sha256()
    data = 'I am frank. hello everyone!'.encode('utf-8')
    sha.update(data)
    print(sha.digest())
    print(sha.hexdigest())


def sha3_512_test():
    sha3_512 = hashlib.sha3_512()
    data = 'I am frank. hello everyone!'.encode('utf-8')
    sha3_512.update(data)
    # 返回二进制的加密结果
    print(sha3_512.digest())
    # 返回十六进制的机密结果
    print(sha3_512.hexdigest())


if __name__ == '__main__':
    md5_test()
    print("***" * 20)
    sha256_test()
    print("***" * 20)
    sha3_512_test()
    

常用方法 介绍

  1. hash.update(arg)

Update the hash object with the object arg, which must be interpretable as a buffer of bytes. Repeated calls are equivalent to a single call with the concatenation of all the arguments: m.update(a); m.update(b) is equivalent to m.update(a+b).

用来更新 要加密的参数
注意: update()方法现在只 接受bytes类型的数据
hash.update(b'frank'), hash.update(b'hello') == hash.update(b'frankhello')

  1. hash.digest()

Return the digest of the data passed to the update() method so far. This is a bytes object of size digest_size which may contain bytes in the whole range from 0 to 255.

返回二进制的加密结果

  1. hash.hexdigest()

Like digest() except the digest is returned as a string object of double length, containing only hexadecimal digits. This may be used to exchange the value safely in email or other non-binary environments.

返回十六进制的加密结果

  1. hash.copy()

Return a copy (“clone”) of the hash object. This can be used to efficiently compute the digests of data sharing a common initial substring.

复制一个hash 对象

  1. hash.digest_size

The size of the resulting hash in bytes. 属性, 返回 hash 结果多少 bytes

  1. hash.block_size

The internal block size of the hash algorithm in bytes. 属性 , 返回 内部块 占用 多少 bytes

2. 还可以用传字符串 来 调用算法. 生成摘要

1 . 通过调用 hashlib.new(str, data)



import hashlib
h=hashlib.new('md5',b'frank')  
h.digest()
Out[42]: b'&%x1f\xaa\x9c.+\x83gs\xc6\x9f\xe6'
h.digest_size
Out[43]: 16
'&%x1f\xaa\x9c.+\x83gs\xc6\x9f\xe6'.__len__()
Out[44]: 16

    always_supported = ('md5', 'sha1', 'sha224', 'sha256', 'sha384', 'sha512',
                        'blake2b', 'blake2s',
                        'sha3_224', 'sha3_256', 'sha3_384', 'sha3_512',
                        )

    for algorithm in always_supported:
        try:
            h = hashlib.new(algorithm, b"frank")
        except TypeError as e:
            print(e)
            print(algorithm)
        else:
            print(algorithm, end='  ')
            print(h.digest())

结果如下

md5  b'&%
sha1  b"\x86\xa8\xc2\xda\x85'\xa1\xc6\x97\x8b\xdc\xa6\xd7\x98o\xe1J\xe1G\xfe"
sha224  b':D/\x05\xd1)\xa9\xbf\x97\xa2\xe0\xa2\xd4\xefl\xc1\xf2\x0b\x1b1\xff\xa8w\xb4\x85\x04p\xd0'
sha256  b"wdoZO1fcv'\xab\xe9\x98\xe7\xa1G\x0f\xe7-\x8bC\x0f\x06}\xaf\xa8bc\xf1\xf2?\x94"
sha384  b'\x04\x14\xbe\xed\xbb\xd8NV\xcaY\xb0\x0c\xe69\x8f\x05\x81`\xdfo\xef\xfe]\xf18C\x1d\xdf\x98\xef\xa8\x8f\x82;\xacGjQ\xdb\xfe\xf1H\xce,Wo}\x0f'
sha512  b'\x19\xb7\x02\xb6\xf1\xb15\xca\x00\x9c\xe1\xdf\x13\xd8G8\xb7L\xb7DZ\xf6=\xd3o/\xde\xfew\xdf\x83\xfc\xde\xcf0}\xb56\t5($,<\xe5*\x93PEZ\xcb\x1e\x8a\xd9\x06\xfc\xcd@\xfd\tZ\xba\xb4\xf1'
blake2b  b'\xbe5\x9e\xe2\x9c\x96\x95`?\x91\x89\xc5\xa8\x12\xdc\xd24\xf2\xd3\x0c}\xeb\xaa\xf5\xe4h|\xc0F[\r@\xbe\xe2)\x03\xbc~C\xb8"2S\xbc\xb6\xe3\xcb\xf2\xa9\xd6\x02\xaf\xb2\x19\x1cn\xa6"\xca\xf6G\xcd\x9f\x84'
blake2s  b'({E\x0c\x1ed\xfd\xe4}@\xd9\x91`\xa6\x81O(V\xa3$l\x03\x8f\x879\xeb\x89\xe2\x97\x13\xf0\xcd'
sha3_224  b'\x07\xd0(\xa1\xda\x99\x8a\xbf\x98\xb5\x835\xbf\x99\xff\xa0\xcf\x80\xab\xeb\xab\x0ec\x9d\x16\xbd\xa1\x8d'
sha3_256  b"'\x1e9\n\xf7}\x17#\xcd\x03\xfa\x18\xb9\x10C3\xe1\x1c\xee/\xbd\xd8\x02\t\x00\x8a\x1d|\x0f\xba\x14\x04"
sha3_384  b'\x05C\x88,8\x8b\xbb\xbf\x1e^~\x88\xc3\xd6H*\xad\xfc\xf2\xca\xb4\xec\xc0\x12B\x00\xaa\xd6\x84\xe6n\x81\xa8\xcez\x1dT|\x07Hh\xdb\xbf?\xa8\xc0\xeb\xb1'
sha3_512  b"\xff\xfd\xbd\xe6\xe3\x0f5\x02\xab\xcb\x83\x8e\x07C\xad\xbc\xaeI\xfb'U\xcb\xd9\xd3\x8a\x87\xaa\xb9ZU\xc9\xf7\xbbfH\xf5\xc2j~L\x91R\x86S\xef\x8a\xc1\x0e\xef\xf6\x02d\x0b\xa7\xdc\x12\xac\xe0\xfc\xd1`\x9b7*"
3. 'shake_128', 'shake_256'

对于 shake_128 , shake_256 算法 需要传入参数 一个 length

The shake_128() and shake_256() algorithms provide variable length digests with length_in_bits//2 up to 128 or 256 bits of security. As such, their digest methods require a length. Maximum length is not limited by the SHAKE algorithm.

shake.digest(length)
Return the digest of the data passed to the update() method so far. This is a bytes object of size length which may contain bytes in the whole range from 0 to 255.

shake.hexdigest(length)
Like digest() except the digest is returned as a string object of double length, containing only hexadecimal digits. This may be used to exchange the value safely in email or other non-binary environments.



if __name__ == '__main__':
   # h = hashlib.new('shake_128', b'frank')
   h = hashlib.new('shake_256', b'frank')

   print(h.digest(16))

   print(h.hexdigest(16))
   print(h.hexdigest(16).__len__()) 
   
# 结果如下
# b'~\xf6\xfb\xe6\x8f\xc9\xcf\xa7D\x9c\x97\xfa\xad_\xa16'
# 7ef6fbe68fc9cfa7449c97faad5fa136
# 32


4 blake2b', 'blake2s, python3.6 添加

可以用来作网站的安全认证.

https://docs.python.org/3/library/hashlib.html#hashlib.blake2b

def  hashlib_blask2b_test():
   # 指定长度
   h = hashlib.blake2b(digest_size=16)
   h.update(b'frank')
   print(h.hexdigest())

def hashlib_blaske2b_key():
   # 可以指定key
   h = hashlib.blake2b(key=b'this is your name',digest_size=16)
   h.update(b'frank')
   print(h.hexdigest())
   


if __name__ == '__main__':

   hashlib_blask2b_test()
   hashlib_blaske2b_key()
   
   
5 总结

简单说明 hashlib 模块的使用, 当然还有一些没有涉及到.具体更多内容请参考官网.

参考资料

https://zh.wikipedia.org/wiki/SHA家族
https://docs.python.org/3/library/hashlib.html
http://wiki.jikexueyuan.com/project/explore-python/Standard-Modules/hashlib.html
http://www.liujiangblog.com/course/python/58

分享快乐,留住感动.2018-07-07 22:30:45 --frank

你可能感兴趣的:(python基础&进阶)