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 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86
| import os import hashlib import sqlite3 import binascii
def encrypt_passwd(passwd, salt=None): if salt is None: salt = binascii.b2a_hex(os.urandom(8)) passwd = passwd.encode('utf-8') result = hashlib.pbkdf2_hmac('sha256', passwd, salt, 10000)
return salt + binascii.b2a_hex(result)
def verify_passwd(salthash, passwd): if isinstance(salthash, str): salthash = salthash.encode('utf-8')
return encrypt_passwd(passwd, salt=salthash[:16]) == salthash
def init_db():
conn = sqlite3.connect("user.db") c = conn.cursor() c.execute("DROP TABLE IF EXISTS USER;") sql = """CREATE TABLE USER( ID INTEGER PRIMARY KEY autoincrement, USERNAME TEXT NOT NULL, PASSWORD TEXT NOT NULL); """ c.execute(sql) conn.commit() return conn
def register(conn, username, passwd): c = conn.cursor() passwd = encrypt_passwd(passwd).decode('utf-8')
c.execute("INSERT INTO USER (ID,USERNAME,PASSWORD) VALUES (NULL,?,?)", (username, passwd)) conn.commit() print("注册%s成功!" % (username))
def sgin(conn, username, passwd): c = conn.cursor() cur = c.execute("SELECT PASSWORD from USER where USERNAME=:name", {"name": username}) pwd = cur.fetchone() if pwd and verify_passwd(pwd[0], passwd): print('登录%s成功!' % (username)) return True else: print("登录%s失败" % (username)) return False
if __name__ == '__main__': c = init_db() register(c, "zhang3", "123456") register(c, "li4", "212") sgin(c, "zhang3", "1234") sgin(c, "li", "12") while True: user = input("user:") passwd = input("passwd:") if sgin(c, user, passwd): break c.close()
|