python嵌套字典可存储用户名和密码

时间:2018-11-02 23:46:06

标签: python-2.7 dictionary hash nested multiple-users

我要创建的是一个字典,用于存储来自用户输入的哈希用户名和密码...现在,我不得不承认我不完全了解嵌套字典的工作原理,但是到目前为止,这是我的函数代码:

users = {}    
def addUser():
    print """"
    ########
    Add user
    ########
    """
    while True:
        username = hashlib.sha512(raw_input("Enter username: ")).hexdigest()
        passwd = hashlib.sha512(raw_input("Enter password: ")).hexdigest()
        uid = int(username[:5], 16) % 32

        users[username + passwd] = {
            'User hash':username,
            'Password hash':passwd,
            }

        print users
        cont = raw_input("Press 'X/x' to exit and start the server or ANY other key to continue adding users: ")
        if cont in ['X', 'x']:
            break

我想做的是使用uid变量为每个用户生成一个唯一的标识符,并将其存储在一个嵌套的字典中,该字典看起来像这样:

users = { 'uid': 28 { 'User hash': 'BFCDF3E6CA6CEF45543BFBB57509C92AEC9A39FB', 'Password hash': '9D989E8D27DC9E0EC3389FC855F142C3D40F0C50'},'uid': 10 { 'User hash': '8C4947E96C7C9F770AA386582E32CE7CE1B96E69', 'Password hash': '266F83D202FA3DA4A075CEA751B4B8D6A30DA1A8'}

}

1 个答案:

答案 0 :(得分:0)

阅读并玩弄代码后回答了我自己的问题。

如果其他人遇到类似的问题,这是已解决的代码

import hashlib

users = {}
def addUser()
    print """"
    ########
    Add user
    ########
    """
    while True:
    username = hashlib.sha512(raw_input("Enter username: ")).hexdigest()    #use SHA512 to hash username from raw input
    uid = int(username[:5], 16) % 32                                        #generate uid from hashed username, using math simliar to the chord algorithm but with SHA512 instead of SHA1
    passwd = hashlib.sha512(raw_input("Enter password: ")).hexdigest()      #use SHA512 to hash password from raw input


    users[uid] = {   #store username and password in dictionary 
        'User hash':username,
        'Password hash':passwd,
        }


    print users
    cont = raw_input("Press 'X/x' to exit and start the server or ANY other key to continue adding users: ")
    if cont in ['X', 'x']:
        break

我通过查看print users调用实际上做了什么来解决这个问题,并打印了两个哈希的组合,因此用users[username + passwd]替换users[uid]解决了这个问题!

故事的寓意:如果它不起作用...做一些研究,找个玩耍,然后再努力! ;)