#!/usr/bin/env python
# -*- encoding: UTF-8 -*-

#hashlib MD5摘要算法，写个小小的注册，登录
import hashlib
import re
import json

def get_md5(mix_password):
    md5 = hashlib.md5()
    md5.update(mix_password.encode('utf-8'))
    return md5.hexdigest()

def register():
    print('-'*15,'Register','-'*20)
    username = input('Please input your username:')
    password = input('Please input your password:')
    if 5<len(username)<17 and 5<len(password)<17:
        with open('register.txt','r') as fr:
            db = fr.read()
            passwordNB = get_md5(password+username+'the-salt')
            db_no_k = re.sub('[\}]','',db)
        with open('register.txt','w') as fw:
            add_db = db_no_k+','+'"'+username+'"'+':'+'"'+passwordNB+'"'+'}'
            fw.write(add_db)
            print('Register success!please login')
        login()
    else:
        print('username and password must be 6-16 characters,try again')
        register()

def login():
    print('-'*15,'login','-'*20)
    with open('register.txt','r') as f:
        database = f.read()
        database = re.sub('[\s]','',database)
        dict_database = json.loads(database)
    usn = input('Please enter your username:')
    pwd = input('Please enter your password:')
    if usn in dict_database:
        md5 = hashlib.md5()
        md5.update((pwd+usn+'the-salt').encode('utf-8'))
        pwding =md5.hexdigest()
        if pwding == dict_database[usn]:
            print('longin success')
        else:
            print('Password is not match,Please try again!')
    else:
        print('Username is not exist,please register first!')
        register()
login()




