【问题标题】:python nested dictionaries to store usernames and passwordspython嵌套字典来存储用户名和密码
【发布时间】:2019-04-07 04:48:51
【问题描述】:

我正在尝试创建的是一个字典,它存储来自用户输入的散列用户名和密码......现在诚然,我认为我并不完全理解嵌套字典的工作原理,但这是我的函数的代码到目前为止:

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'}

}

【问题讨论】:

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


    【解决方案1】:

    在阅读和使用代码后回答了我自己的问题。

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

    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] 解决了这个问题!

    故事的寓意:如果它不起作用......做一些研究,玩一玩并更加努力! ;)

    【讨论】:

      猜你喜欢
      • 2020-10-27
      • 1970-01-01
      • 2013-12-27
      • 2010-12-27
      • 1970-01-01
      • 2021-05-17
      • 1970-01-01
      • 2019-07-16
      • 2019-09-02
      相关资源
      最近更新 更多