Repository navigation
Expand file tree
/
Copy pathwork_hmac.py
More file actions
65 lines (51 loc) · 1.7 KB
/
Copy pathwork_hmac.py
File metadata and controls
65 lines (51 loc) · 1.7 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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Created by TaoYuan on 2017/12/15 0015.
# @Link : http://blog.csdn.net/lftaoyuan
# Github : https://github.com/seeways
# @Remark : Python学习群:315857408
# work_md5_salt的salt改为标准的hmac算法,验证用户口令
import hmac
import random
def hmac_md5(key, s):
return hmac.new(key.encode('utf-8'), s.encode('utf-8')).hexdigest() # 默认md5
class User(object):
def __init__(self, username, password):
self.username = username
self.password = hmac_md5(username, password + create_salt(username))
def create_salt(username):
salt = ''
chars = 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz0123456789'
len_chars = len(chars) - 1
for i in range(5):
# 每次从chars中随机取一位
salt += chars[random.randint(0, len_chars)]
if username in db:
return salt_db[username]
else:
salt_db[username] = salt
return salt_db[username]
db = {}
salt_db = {}
def regist(username, password):
if username in db:
print("username existed!")
else:
db[username] = User(username, password)
def login(username, password):
user = db[username]
return hmac_md5(username, password + create_salt(username)) == user.password
if __name__ == '__main__':
# register
regist('michael', '123456')
login('michael', '123456')
regist('bob', 'abc999')
regist('alice', 'alice2008')
# login:
assert login('michael', '123456')
assert login('bob', 'abc999')
assert login('alice', 'alice2008')
assert not login('michael', '1234567')
assert not login('bob', '123456')
assert not login('alice', 'Alice2008')
print('ok')