Skip to content

Commit 166f791

Browse files
authored
练习内建模块之hmac
1 parent add7307 commit 166f791

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed

test43.py

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
#!/usr/bin/env python3
2+
# -*- conding: utf-8 -*-
3+
4+
'练习内建模块之hmac'
5+
6+
__author__ = 'sergiojune'
7+
import random, hmac # 这个模块是可以根据口令进行加密保存数据,相当于md5加slat的效果,还比他强
8+
message = b'hello world'
9+
key = b'key'
10+
# 第一个和第二个参数都必须是bytes类型
11+
p = hmac.new(key, message, digestmod='md5') # 指定md5算法,一个参数为口令,第二个为加密的信息
12+
print(p.hexdigest())
13+
14+
15+
# 作业:将上一节的salt改为标准的hmac算法,验证用户口令
16+
def hmac_md5(key, s):
17+
return hmac.new(key.encode('utf-8'), s.encode('utf-8'), 'MD5').hexdigest()
18+
19+
20+
class User(object):
21+
def __init__(self, username, password):
22+
self.username = username
23+
self.key = ''.join([chr(random.randint(48, 122)) for i in range(20)])
24+
self.password = hmac_md5(self.key, password)
25+
26+
27+
db = {
28+
'michael': User('michael', '123456'),
29+
'bob': User('bob', 'abc999'),
30+
'alice': User('alice', 'alice2008')
31+
}
32+
33+
34+
def login(username, password):
35+
user = db[username]
36+
return user.password == hmac_md5(user.key, password)
37+
38+
39+
# 测试:
40+
assert login('michael', '123456')
41+
assert login('bob', 'abc999')
42+
assert login('alice', 'alice2008')
43+
assert not login('michael', '1234567')
44+
assert not login('bob', '123456')
45+
assert not login('alice', 'Alice2008')
46+
print('ok')

0 commit comments

Comments
 (0)