python常用模块—-hashlib

python常用模块——hashlib

1
2
3
4
> python的hashlib提供了常见的摘要算法,如MD5,SHA1等
> 摘要算法又称为hash算法、散列算法。它通过一个函数把任意长度的数据转换为一个长度的固定的数据串(通常用十六进制字符串表示)
> 摘要算法反推很困难,因为摘要函数是单向的,对原始数据做一个bit的修改,都会导致计算出的摘要完全不同
>

hashlib模块学习

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#coding:utf-8
import hashlib

md5 = hashlib.md5()
md5.update('how to use md5 in python hashlib?')
#使用生成实例的update方法进行MD5的转换,同时,update会将每次的字符串拼接,如果想要不同的值,每次过后都得实例化
print md5.hexdigest() #返回摘要信息,以十六进制数据返回
print md5.digest() #返回摘要信息,以二进制数据返回

#刚才说过的update,如果数据量很大,可以使用它拼接
#MD5是最常见的摘要算法,速度很快,生成结果是固定的128 bit字节,通常用一个32位的16进制字符串表示
md52 = hashlib.md5()
md5.update('how to use md5 in')
md5.update('python hashlib?')
print md5.hexdigest()

#SHA1的结果是160 bit字节,通常用一个40位的16进制字符串表示
#有没有可能两个不同的数据通过某个摘要算法得到了相同的摘要?完全有可能,因为任何摘要算法都是把无限多的数据集合映射到一个有限的集合中。这种情况称为碰撞
sha1 = hashlib.sha1()
sha1.update('how to use sha1 in ')
sha1.update('python hashlib?')
print sha1.hexdigest()

实例

1.进行hash爆破:

1
2
3
4
5
6
7
8
9
10
11
12
#coding:utf-8
import string
import hashlib

a = string.digits + string.lowercase + string.uppercase
for i in a:
for j in a:
for k in a:
for m in a:
s = hashlib.md5(i+j+k+m).hexdigest()[0:6]
if s == '9bf514':
print i+j+k+m

2.用hashlib模拟用户登录,以及password值加盐存储:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
#coding:utf-8
import re, hashlib
dic = { 'syq123': '506420d6fc050439850f1cb80eb70b9c',
'feifei': 'f95f65d787a87a5e3d32c61b3f7e9bec',
'zsg123': '87c34b8d2950946df7a987a990cad99f'}

def get_md5(password):
md5 = hashlib.md5()
md5.update(password)
return md5.hexdigest()


def Salt_get_md5(password,name):
return get_md5(password + name + 'salt')


def username():
#创建用户
name = raw_input('please input your username!!')
if re.match(r'^[a-zA-Z].{2,9}',name):
userpassword(name)
else:
print 'input error!'
username()

def userpassword(name):
password = raw_input('please input your password:')
password = Salt_get_md5(password,name)
print password
dic[name] = password #这里如果用update方法时会出现一个问题,添加进字典的不是变量对应的值,而是输入的变量名称
print dic

def login():
str = 'Please Login'
print str.center(25)
name = raw_input('please input your username:')
password = raw_input('please input your password:')
password = Salt_get_md5(password,name)
if dic[name] == password:
print 'Login Success!'
else:
print 'Login faild! username or password error!'
login()

if __name__ == '__main__':
ch = raw_input('请选择1或2:1->登录,2->注册')
# print type(ch)
if ch == '1':
login()
elif ch == '2':
username()
ch = raw_input('请选择1或2:1->登录,2->退出')
if ch == '1':
login()
elif ch =='2':
exit('bye!!!')