Python 常用函数 hashblib模块

hash:一种算法 ,3.x里代替了md5模块和sha模块,主要提供 SHA1, SHA224, SHA256, SHA384, SHA512 ,MD5 算法;

三个特点:

1.内容相同则hash运算结果相同,内容稍微改变则hash值则变
2.不可逆推
3.相同算法:无论校验多长的数据,得到的哈希值长度固定。

应用:

import hashlib

#1、md5加密
hash = hashlib.md5()
hash.update('hello'.encode('utf-8'))
hash.update('Yim'.encode('utf-8'))              #这两条加起来等同于'hello Yim'
print(hash.hexdigest())

#2、sha1加密
hash = hashlib.sha1()
hash.update('hello Yim'.encode('utf-8'))
print(hash.hexdigest())

#3、添加自定义key进行加密
hash = hashlib.sha1('python'.encode('utf-8'))
hash.update('hello Yim'.encode('utf-8'))
print(hash.hexdigest())

#4、hmac加密
#hmac内部对我们创建的key和内容进行处理后再加密
import hmac
h = hmac.new('python'.encode('utf-8'))
h.update('hello Yim'.encode('utf-8'))
print(h.hexdigest())

#5、获取大文件的md5
hash = hashlib.md5()
with open('a.txt','rb') as f:
    for line in f:
        hash.update(line)
print(hash.hexdigest())

#6、模拟撞库破解密码
import hashlib

passwds = [
    'hello',
    'hello word',
    'hello yim',
    'hello Yim',
]

def make_passwd_dict(passwds):
    dict = {}
    for i in passwds:
        hash = hashlib.sha1()
        hash.update(i.encode('utf-8'))
        dict[i] = hash.hexdigest()
    return dict

def break_code(cryptograph,passwd_dic):
    for k,v in passwd_dic.items():
        if v == cryptograph:
            print('密码是:%s'%k)

cryptograph = '9c68ef3cca853cd2c1c286bde3534693c9c11ed1'
break_code(cryptograph,make_passwd_dict(passwds))

  

posted on 2017-08-17 20:36  wangyinhu1208  阅读(223)  评论(0编辑  收藏  举报