简体   繁体   English

如何在 SQLite3 数据库上存储散列密码?

[英]How to store hashed passwords on SQLite3 database?

I want to store passwords on a sqlite3 database on python, however I don't want to store the passwords in plaintext for obvious reasons.我想将密码存储在 python 上的 sqlite3 数据库中,但是出于明显的原因,我不想以明文形式存储密码。 I have used bcrypt to hash the passwords, but I keep running into issues.我已经使用 bcrypt 到 hash 的密码,但我一直遇到问题。

import tkinter as tk
import bcrypt
import sqlite3

conn = sqlite3.connect('TEST_DB.db')
c = conn.cursor()


class MainApplication():
    def __init__(self, root):
        self.password_var = tk.StringVar()
        password_entry = tk.Entry(root, textvariable=self.password_var)
        password_entry.pack()

        password = self.password_var.get()

        hashable_pw = bytes(password, encoding='utf-8')
        hashed_pw = bcrypt.hashpw(hashable_pw, bcrypt.gensalt())
        print(hashed_pw)

        c.execute("INSERT INTO Accounts (password) VALUES(?)", (hashed_pw,))
        conn.commit()

if __name__ == "__main__":
    root = tk.Tk()
    MainApplication(root)
    root.mainloop()

Printing the hashed password yields the results I want打印散列密码会产生我想要的结果

b'$2b$12$4SPZzQKBSKS1H1WHYRoC6.9pZTy1veZpc6x5MdM/LA1zgoKZWV6I.'

But when I insert that value into the database table, it shows in this format.但是当我将该值插入数据库表时,它会以这种格式显示。

Also, I have attempted to check the hash in the database against the plaintext password entered.此外,我还尝试根据输入的明文密码检查数据库中的 hash。

f = c.execute("SELECT password FROM Accounts WHERE user_ID=1")
        conn.commit()
        print("RETURNED HASH:", f)

        if bcrypt.checkpw(password, hashed_pw):
            print("It matches")
        else:
            print("Didn't match")

I believe based on how the format is shown in the database, there are some formatting issues involving that.我相信根据格式在数据库中的显示方式,存在一些涉及到的格式问题。

Here is the error message这是错误消息

TypeError: Unicode-objects must be encoded before checking

Updated to show database code更新以显示数据库代码

import sqlite3

conn = sqlite3.connect('TEST_DB.db')
c = conn.cursor()

c.execute("""CREATE TABLE Accounts (
            user_id INTEGER PRIMARY KEY AUTOINCREMENT,
            email_address NVARCHAR(320) NOT NULL DEFAULT '',
            password CHAR(60) NOT NULL DEFAULT '',
            )""")
conn.commit()

password = self.password_var.get().encode("utf-8") it should resolve the issue. password = self.password_var.get().encode("utf-8") 它应该可以解决问题。

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

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