修复了导入到MySQL表中时密码哈希被截断的问题

时间:2018-07-09 18:12:11

标签: python mysql flask bcrypt

我目前有一个Flask应用,可将用户名和密码注册到MySQL数据库。我的问题是,使用Bcrypt对密码进行哈希处理,然后将其保存到数据库中,输出的哈希将被MySQL截断。我的功能如下:

class PasswordResource(Resource):
    @app.route('/password', methods=['GET'])
    @jwt_required

    def sendPassword():
        data = get_jwt_identity()
        hashed_password = bcrypt.hashpw(data['user_password'].encode('utf8'), bcrypt.gensalt())
        print(hashed_password)
        return mysqldb.addPassword("{}".format(str(data['user_name'])),"{}".format(hashed_password))

并连接到数据库:

def addPassword(Username,Userpassword):
    try:
        cursorObject = connection.cursor()
        cursorObject.execute("call sp_createPassword('{}'".format(Username)+",'{}')".format(Userpassword))
        connection.commit()
        connection.close()

    finally:
        return 'User added succesfully!'

但是,即使我为密码表尝试了各种VARCHAR(),哈希也被MySql截断。我在控制台Warning: (1265, u"Data truncated for column 'p_password' at row 1") self._do_get_result()中遇到此错误。我的密码列当前配置为VARCHAR(255), Not Null。如何解决此错误并避免哈希值被截断?

更新

这就是我的密码表的架构:

+---------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Table         | Create Table                                                                                                                                                                                                                                                                            |
+---------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| tbl_passwords | CREATE TABLE `tbl_passwords` (
  `user_name` varchar(255) DEFAULT NULL,
  `user_password` varchar(255) NOT NULL,
  `user_number` bigint(20) NOT NULL AUTO_INCREMENT,
  PRIMARY KEY (`user_number`)
) ENGINE=InnoDB AUTO_INCREMENT=12 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci |
+---------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+

1 个答案:

答案 0 :(得分:1)

我的问题在于我的过程sp_createpassword()中添加了密码。在此过程中,我将password参数设置为VARCHAR(20),显然对于哈希值来说还不够。愚蠢的错误。尽管如此,塔德曼的建议对于建立合适的数据库确实很有帮助。