相同的密码哈希函数创建不同的哈希相同的密码

时间:2014-04-08 22:17:30

标签: python hash bottle

我写了一个小瓶子网络应用程序在我的树莓派上运行并控制锅炉。有一个登录页面和一个创建新用户页面。当我创建一个新用户时,它会生成一个salt并使用sha512来散列密码,并且两者都存储在数据库中。当用户登录时,它匹配用户ID并从数据库获取salt和密码哈希,并使用数据库中的salt哈希显示密码,但始终创建​​不同的哈希,以便登录失败。我确定它有点蠢,但我无法对它进行排序。

这是执行密码哈希/检查/盐

的代码
def get_password(userid):
    userid = userid.upper()
    logging.debug('get password for %s' % userid)
    conn_string = prop('database')
    conn = psycopg2.connect(conn_string)
    cursor = conn.cursor()

    sql =   """
            select password, salt from users where userid = %(userid)s
            """
    cursor.execute(sql, {'userid':userid})
    row = cursor.fetchone()
    if row is not None:
        dbpassword = row[0]
        dbsalt = str(row[1])
        logging.debug('db password hash %s' % dbpassword)
        logging.debug('db password salt %s' % dbsalt)
        return dbpassword, dbsalt
    else:
        logging.debug('No details found for user')
        return None, None

def check_password(password, userid):
    logging.debug('username/password to check is %s/%s' % (password, userid))
    dbpassword, dbsalt = get_password(userid)
    if dbpassword is not None:
        test = hash_password(password, dbsalt)
        logging.debug('test password hash %s' % test)
        if test == dbpassword:
            logging.debug('password correct')
            return True
        else: 
            logging.debug('password incorrect')
            return False
    else:
        return False

def hash_password(password, salt):
    if salt == '0':
        logging.debug('hashing password')
        logging.debug('generate salt')
        salt = uuid.uuid4().hex
        logging.debug('salt = %s' % salt)
        hashed_password = crypt(password, salt)
        logging.debug('hashed password = %s' % hashed_password)
        return salt, hashed_password
    else:
        logging.debug('hash password for compare')
        hashed_password = crypt(password, salt)
        logging.debug('hashed password = %s' % hashed_password)
        return hashed_password

def crypt(password, salt):
    hashed_password = hashlib.sha512(password.encode(encoding='utf_8') + salt.encode(encoding='utf_8')).hexdigest()
    return hashed_password

这是从登录页面获取详细信息的位:

def main():
    try:
        rqstSession = request.get_cookie('pysessionid', secret=prop('cookieSecret'))
        username = request.forms.get('username').upper()
        password = request.forms.get('password')
        if request.forms.get('override','').strip() is '':
            if check_password(password, username) is True:
                set_session(rqstSession)            
                return template('main')
        elif check_session(rqstSession) is True:
            if request.forms.get('override','').strip():
                logging.debug('override')
                set_override()
                return template('main')            
            else:
                return template('login')
    except Exception as e:
        logging.debug('exception in main: %s' % e)
        return '<p>Error</p>'

这将从新用户页面获取详细信息:

def new_user():
try:
    rqstSession = request.get_cookie('pysessionid', secret=prop('cookieSecret'))
    if check_session(rqstSession) is True:
        if request.forms.get('save','').strip():
            userid = request.forms.get('userid', '').upper()
            password = request.forms.get('password','')
            confpassword = request.forms.get('confpassword','')
            salt = '0'
            if password is not '' and password == confpassword and userid is not '':
                salt, hashed_password = hash_password(userid, salt)

                conn_string = prop('database')
                conn = psycopg2.connect(conn_string)
                cursor = conn.cursor()

                sql =   """
                        insert into users (id_usrr, userid, password, salt) values (nextval('users_id_usrr_seq'), %(userid)s, %(password)s, %(salt)s)
                        """
                cursor.execute(sql, {'userid':userid, 'password':hashed_password, 'salt':salt})
                conn.commit()
                cursor.close()

            else:
                return template('newuser')
        else:
            return template('newuser')
    else:
        pysessionid = ''
        response.set_cookie('pysessionid', pysessionid, secret=prop('cookieSecret'), Expires='Thu, 01-Jan-1970 00:00:10 GMT', httponly=True)
        return template('main') 
except Exception as e:
    logging.debug(e)
    return '<p>Error</p>'

我尝试去除盐并没有帮助所以我认为它没有任何关系,但我愿意在过去2小时后撞到墙上后尝试任何事情

由于 亚当

1 个答案:

答案 0 :(得分:0)

我不太了解安全性,但我认为这可以解决您的问题

>>> # import the hash algorithm
>>> from passlib.hash import sha256_crypt

>>> # generate new salt, and hash a password
>>> hash = sha256_crypt.encrypt("toomanysecrets")
>>> hash
'$5$rounds=80000$zvpXD3gCkrt7tw.1$QqeTSolNHEfgryc5oMgiq1o8qCEAcmye3FoMSuvgToC'

>>> # verifying the password
>>> sha256_crypt.verify("toomanysecrets", hash)
True
>>> sha256_crypt.verify("joshua", hash)
False

如下所示:

if sha256_crypt.verify("given_pass", db_hash):
    print("you are now logged in")

passlib