Python简要标准库(5)

hashlib


 Python的hashlib提供了常见的摘要算法,如MD5,SHA1等等。

基本的生成MD密匙的函数

1 import hashlib
2 
3 md5 = hashlib.md5()
4 md5.update('This is my password'.encode('utf-8'))
5 print(md5.hexdigest())

 

 

 

若是把password改为了password2

所得到的MD5就完全不一样了

这体现了MD5的单向加密功能的强大

 

若要生成SHA1密匙的话,只需要将功能函数替换即可

 1 sha1 = hashlib.sha1() 



根据用户输入的登录名和口令模拟用户注册,计算更安全的MD5
  使用了shelve模块 存储上次的用户数据信息


 
 1 import hashlib
 2 import shelve
 3 
 4 #注册账号到数据库中   之前检测是否有重复
 5 def Register(db,username,password):
 6     if username in db.keys():
 7         print ('find the same username : ')
 8         return
 9     
10     #生成MD5密匙
11     md5 = hashlib.md5()
12     md5.update((username+password+'something').encode('utf-8'))
13     md5_password = md5.hexdigest()
14     
15     #创建记录
16     user = {}
17     user['password'] = md5_password
18     
19     #保存记录
20     db[username] = user
21     
22     #交互显示
23     print ('Registered successfully!')
24     print ('username : ',username)
25     print ('password : ',password)
26     
27 
28 
29 #显示数据库的信息
30 def showDataBase (db):
31     print ('------This is database show------')
32     for x in db.keys():
33         d = db[x]
34         print ('username : ',x)
35         for key,value in d.items():
36             print (key,':',value)
37     print ('------over------')
38 #登录数据库
39 def SignIn(db,username,password):
40     md5 = hashlib.md5()
41     md5.update((username+password+'something').encode('utf-8'))
42     md5_password = md5.hexdigest()
43     #检测是否有用户账号
44     if username in db.keys():
45         if db[username]['password'] == md5_password:
46             print ('welcome',username)
47         else:
48             print ('password is error')
49     #不存在用户账号信息
50     else:
51         print ('no user call ',username)
52 
53 #获取用户输入
54 def enter_command():
55     cmd = input('Enter command (r,s,q,show) : ')
56     cmd = cmd.strip().lower()
57     return cmd
58 
59 def get_user_input():
60     username = input('pls input your username : ')
61     password = input ('pls input your password : ')
62     L = [username,password]
63     return L
64 def main():
65     database = shelve.open('userData.dat')
66 
67     try:
68         while True:
69             cmd = enter_command()
70             if cmd == 'r':
71                 user_input = get_user_input()
72                 Register(database,user_input[0],user_input[1])
73             elif cmd == 's':
74                 user_input = get_user_input()
75                 SignIn(database,user_input[0],user_input[1])
76             elif cmd == 'show':
77                 showDataBase(database)
78             elif cmd == 'q':
79                 print ('quit by user')
80                 break
81             
82     finally:
83         database.close()
84 
85 if (__name__) == '__main__':
86     main()

 

 

posted on 2016-06-11 20:51  leihui  阅读(281)  评论(0编辑  收藏  举报