Skip to content

Commit add7307

Browse files
authored
练习内建模块之hashlib
1 parent 9c78944 commit add7307

File tree

1 file changed

+83
-0
lines changed

1 file changed

+83
-0
lines changed

test42.py

Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
#!/usr/bin/env python3
2+
# -*- conding: utf-8 -*-
3+
4+
'练习内建模块之hashlib'
5+
6+
__author__ = 'sergiojune'
7+
import random, hashlib # 这个包是用于存储数据,防止别人随意修改数据的类,不能用于加密,因为不支持反推明文
8+
9+
s = 'my name is sergiojune'
10+
# 进行MD5保密
11+
md = hashlib.md5()
12+
md.update(s.encode('utf-8')) # 指定编码方式
13+
# 获取加密后的值
14+
print(md.hexdigest())
15+
# 修改一点内容后
16+
s = 'my name is june'
17+
md5 = hashlib.md5()
18+
md5.update(s.encode('utf-8'))
19+
print(md5.hexdigest()) # 通常结果是128位的bit,用32位的16进制表示
20+
21+
22+
# 使用sha1,用法与md5一样
23+
sha = hashlib.sha1()
24+
sha.update(s.encode('utf-8'))
25+
print(sha.hexdigest()) # 结果是160位的bit,用40位的16进制表示
26+
27+
# 作业1:设计一个验证用户登录的函数,根据用户输入的口令是否正确,返回True或False
28+
db = {
29+
'michael': 'e10adc3949ba59abbe56e057f20f883e',
30+
'bob': '878ef96e86145580c38c87f0410ad153',
31+
'alice': '99b1c2188db85afee403b1536010c2c9'
32+
}
33+
34+
35+
def login(user, passwd):
36+
m = hashlib.md5()
37+
m.update(passwd.encode('utf-8'))
38+
return db[user] == m.hexdigest()
39+
40+
41+
# 测试:
42+
assert login('michael', '123456')
43+
assert login('bob', 'abc999')
44+
assert login('alice', 'alice2008')
45+
assert not login('michael', '1234567')
46+
assert not login('bob', '123456')
47+
assert not login('alice', 'Alice2008')
48+
print('ok')
49+
50+
51+
# 作业2:根据用户输入的登录名和口令模拟用户注册,计算更安全的MD5
52+
def get_md5(s):
53+
return hashlib.md5(s.encode('utf-8')).hexdigest()
54+
55+
56+
class User(object):
57+
def __init__(self, username, password):
58+
self.username = username
59+
self.salt = ''.join([chr(random.randint(48, 122)) for i in range(20)])
60+
self.password = get_md5(password + self.salt)
61+
62+
63+
db = {
64+
'michael': User('michael', '123456'),
65+
'bob': User('bob', 'abc999'),
66+
'alice': User('alice', 'alice2008')
67+
}
68+
69+
70+
def login(username, password):
71+
user = db[username]
72+
password = password + user.salt
73+
return user.password == get_md5(password)
74+
75+
76+
# 测试:
77+
assert login('michael', '123456')
78+
assert login('bob', 'abc999')
79+
assert login('alice', 'alice2008')
80+
assert not login('michael', '1234567')
81+
assert not login('bob', '123456')
82+
assert not login('alice', 'Alice2008')
83+
print('ok')

0 commit comments

Comments
 (0)