如何将哈希密码存储到数据库?
我正在使用 Python 3 和 mysql.connector 模块。我无法将密码存储到数据库中。
这是我的代码:
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 )
感谢您的帮助。
I'm using Python 3
and mysql.connector
module. I could not store the hased password to the database.
Here is my code:
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()
When I run the INSERT
statement, the error occurred:
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
Noted: My datatype for password
is CHAR(96)
I appreciate your help.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
使用查询参数而不是字符串格式。
这两种方法都使用
%s
作为占位符,这有点令人困惑,因为它看起来像是在做同样的事情。但后者并不是做简单的字符串替换。它通过转义特殊字符或执行真实的查询参数,使值对于 SQL 查询来说是安全的,在解析查询之前保持值独立。Use query parameters instead of string-formatting.
Both methods use
%s
as a placeholder, which is kind of confusing because it looks like it's doing the same thing. But the latter is not doing simple string substitution. It makes the value safe for the SQL query, either by escaping special characters, or by doing true query parameters, keeping the value separate until after the query has been parsed.