繁体   English   中英

如何将散列密码存储到数据库?

[英]How to store a hashed password to database?

我正在使用Python 3mysql.connector模块。 我无法将 hased 密码存储到数据库中。

这是我的代码:

import bcrypt
import base64, hashlib
import mysql.connector

class test:
    def __init__(self):
        self.cnx = mysql.connector.connect(**Connect)
        self.cursor = self.cnx.cursor()

        pw = "Test123!"
        password=pw.encode('utf-8')
        
        hash_pass = bcrypt.hashpw(base64.b64encode(hashlib.sha256(password).digest()),bcrypt.gensalt())
        print(hash_pass)

        self.cursor.execute("INSERT INTO test (password) VALUE ('%s')" % (hash_pass))
        self.cnx.commit()

test()

当我运行INSERT语句时,出现错误:

mysql.connector.errors.ProgrammingError: 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '$2b$12$2Jo8.yam0VU5IKQxMa4EV.ReuFGeG43wmzbrFDsT5Pr5c8L2rmlP6'')' at line 1

注意:我的password数据类型是CHAR(96)

我感谢您的帮助。

使用查询参数而不是字符串格式。

// WRONG
self.cursor.execute("INSERT INTO test (password) VALUE ('%s')" % (hash_pass))

// RIGHT
self.cursor.execute("INSERT INTO test (password) VALUE (%s)", (hash_pass,))

这两种方法都使用%s作为占位符,这有点令人困惑,因为它看起来像是在做同样的事情。 但后者并没有进行简单的字符串替换。 它使 SQL 查询的值安全,通过 escaping 特殊字符,或通过执行真正的查询参数,在查询被解析之前保持值分离。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM