Python ASCII控制字符28,29,30和31

时间:2016-01-25 20:16:18

标签: python utf-8 ascii

我正在为学校的项目创建一个简单的数据库样式程序,我使用简单的哈希和salt算法来存储密码。我想使用单位分隔符和记录分隔符ASCII代码来分隔数据库中的属性和记录,但我无法在Python中找到任何内容。到目前为止,这是我的代码:

import os
import hashlib
import sys

users = {}

def new_user():
    while True:
        username = str(input('Please Enter Your Desired Username > '))
        if username in users.keys():
            print('Username already exists, please try again')
        else:
            break
    while True:
        password = str(input('Please Enter a Password Longer than 5 Characters > '))
        if len(password) < 6:
            print('Too Short, Try Again')
        else:
            break
    password = str.encode(password)
    salt = os.urandom(256)
    hashed = hashlib.sha256(password+salt).hexdigest()
    new = {'username' : username,
           'password' : hashed,
           'salt' : salt }
    users[username] = new
    towrite = new['username']+'\x1f'+new['password']+'\x1f'+str(new['salt'])+'\x1e'
    with open('users.txt', 'a') as userfile:
        userfile.write(towrite)
    print('New User Created: Welcome %s' % username)
    return()

def login():
    while True:
        with open('users.txt', 'r') as userfile:
            users = userfile.read().split('\x1e')
            for user in users:
                user = user.split('\x1f')
        username = str(input('Please Enter Your Username > '))
        password = str(input('Please Enter Your Password > '))
        salt = user[2]
        password = hashlib.sha256(password + salt).hexdigest()
        for user in users:
            if (username == user[0]) and (password == user[1]):
                print('You\'re In!')
                return()
        print('Invalid Username or Password')

while True:
    choice = str(input('Continue Adding? > '))
    if choice == 'n':
        break
    else:
        new_user()

while True:
    choice = str(input('Continue Logging? > '))
    if choice == 'n':
        break
    else:
        login()

这里的问题是,当连接new_user()函数中的属性时,写入文件的字符串不包含&#39; \ x1e&#39;或&#39; \ x1f&#39;。我该如何解决这个问题或以其他方式实现这些控制代码?

0 个答案:

没有答案