hashlib模块

"""hashlib模块—许多散列函数的通用接口。

new(name, data=b'') - 返回实现的新散列对象。 哈希函数;初始化散列 使用给定的二进制数据。

命名构造函数也可用。, 下面这些都比构造函数快:

md5(), sha1(), sha224(), sha256(), sha384(), and sha512()

md5加密:不可逆的加密算法
明智地选择你的哈希函数。. Some have known collision weaknesses. sha384和sha512将在32位平台上运行缓慢 Hash objects have these methods: - update(arg): 用arg中的字节更新散列对象。 Repeated calls are equivalent to a single call with the concatenation of all the arguments. - digest(): 返回传递给update()方法的字节摘要。 - hexdigest(): 就像digest(),除了摘要作为unicode返回。 双长度对象,仅包含十六进制数字 - copy(): 返回散列对象的复制(克隆)。这是通常可以有效地计算共享一个共同的字符串的摘要。 最初的子字符串。 For example, to obtain the digest of the string 'Nobody inspects the spammish repetition': >>> import hashlib >>> m = hashlib.md5() >>> m.update(b"Nobody inspects") >>> m.update(b" the spammish repetition") >>> m.digest() b'\\xbbd\\x9c\\x83\\xdd\\x1e\\xa5\\xc9\\xd9\\xde\\xc9\\xa1\\x8d\\xf0\\xff\\xe9' More condensed: >>> hashlib.sha224(b"Nobody inspects the spammish repetition").hexdigest() 'a4337bc45a8fc544c03f52dc550cd6e1e87021bc896588bd79e901e2'
"""
 1 #!/usr/bin/env python
 2 # -*- encoding:utf-8 -*-
 3 import hashlib
 4 
 5 
 6 def md5(arg):
 7     """
 8     对密码进行md5加密
 9     :param arg: 密码
10     :return: 返回unicode编码 双长度对象,仅包含十六进制数字
11     """
12     haha = hashlib.md5(bytes('jove', encoding="utf-8"))
13     haha.update(bytes(arg, encoding='utf-8'))
14     return haha.hexdigest()
15 
16 
17 def login(username, password):
18     """
19     登录
20     :param username: 用户名
21     :param password: 密码
22     :return: True,login success, False,login fail
23     """
24     with open('db', 'r', encoding='utf-8') as f:
25         for line in f:
26             line_list = line.strip().split("|")
27             if line_list[0] == username and line_list[1] == md5(password):
28                 return True
29     return False
30 
31 
32 def register(username, password):
33     """
34     注册
35     :param username: 用户名
36     :param password: 密码
37     :return: True,register success, False,register fail
38     """
39     with open('db', 'a', encoding='utf-8') as  f:
40         temp = "\n" + username + "|" + md5(password)
41         f.write(temp)
42         return True
43     return False
44 
45 
46 while True:
47     choice = input("1.login------2.register")
48 
49     if choice == '1':
50         username = input("please input username:")
51         password = input("please input password:")
52         flag = login(username, password)
53         if flag:
54             print("login success")
55         else:
56             print("login fail")
57     elif choice == '2':
58         username = input("please input username:")
59         password = input("please input password:")
60         register(username, password)

 

posted on 2018-01-17 22:31  jovelove  阅读(90)  评论(0编辑  收藏  举报