简体   繁体   中英

How to store a hashed password to database?

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.

Use query parameters instead of string-formatting.

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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