Uh oh!
There was an error while loading. Please reload this page.
forked from SergioJune/python_test
- Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathtest42.py
More file actions
Latest commit
83 lines (63 loc) · 2.31 KB
/
Copy pathtest42.py
File metadata and controls
83 lines (63 loc) · 2.31 KB
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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
#!/usr/bin/env python3
# -*- conding: utf-8 -*-
'练习内建模块之hashlib'
__author__='sergiojune'
importrandom, hashlib# 这个包是用于存储数据,防止别人随意修改数据的类,不能用于加密,因为不支持反推明文
s='my name is sergiojune'
# 进行MD5保密
md=hashlib.md5()
md.update(s.encode('utf-8')) # 指定编码方式
# 获取加密后的值
print(md.hexdigest())
# 修改一点内容后
s='my name is june'
md5=hashlib.md5()
md5.update(s.encode('utf-8'))
print(md5.hexdigest()) # 通常结果是128位的bit,用32位的16进制表示
# 使用sha1,用法与md5一样
sha=hashlib.sha1()
sha.update(s.encode('utf-8'))
print(sha.hexdigest()) # 结果是160位的bit,用40位的16进制表示
# 作业1:设计一个验证用户登录的函数,根据用户输入的口令是否正确,返回True或False
db= {
'michael': 'e10adc3949ba59abbe56e057f20f883e',
'bob': '878ef96e86145580c38c87f0410ad153',
'alice': '99b1c2188db85afee403b1536010c2c9'
}
deflogin(user, passwd):
m=hashlib.md5()
m.update(passwd.encode('utf-8'))
returndb[user] ==m.hexdigest()
# 测试:
assertlogin('michael', '123456')
assertlogin('bob', 'abc999')
assertlogin('alice', 'alice2008')
assertnotlogin('michael', '1234567')
assertnotlogin('bob', '123456')
assertnotlogin('alice', 'Alice2008')
print('ok')
# 作业2:根据用户输入的登录名和口令模拟用户注册,计算更安全的MD5
defget_md5(s):
returnhashlib.md5(s.encode('utf-8')).hexdigest()
classUser(object):
def__init__(self, username, password):
self.username=username
self.salt=''.join([chr(random.randint(48, 122)) foriinrange(20)])
self.password=get_md5(password+self.salt)
db= {
'michael': User('michael', '123456'),
'bob': User('bob', 'abc999'),
'alice': User('alice', 'alice2008')
}
deflogin(username, password):
user=db[username]
password=password+user.salt
returnuser.password==get_md5(password)
# 测试:
assertlogin('michael', '123456')
assertlogin('bob', 'abc999')
assertlogin('alice', 'alice2008')
assertnotlogin('michael', '1234567')
assertnotlogin('bob', '123456')
assertnotlogin('alice', 'Alice2008')
print('ok')