【问题标题】:validating encrypted data from sqlite3 database验证来自 sqlite3 数据库的加密数据
【发布时间】:2022-12-18 01:32:46
【问题描述】:

我正在创建一个登录功能,其中一部分包括检查用户输入的密码与存储在数据库中的密码。

问题是,当在注册步骤中创建密码时,它使用 fernet 存储为加密字符串。现在我试着看看用相同的密钥加密用户输入的密码是否会产生与数据库中相同的加密字符串值,但是 fernet 将在相同的明文上使用相同的密钥创建唯一的字符串。

还有什么其他方法可以检查输入的密码与数据库中的加密对应密码?

import sqlite3
from cryptography.fernet import Fernet
key = Fernet.generate_key()
fernet = Fernet(key)

def loginFunc():
  email = input("What is your email: ")
  password = input("what is your password: ")
  #a variable that can be used to save the data from users database
  emailList = '''SELECT * FROM users WHERE `email` = ? and `password` = ?'''
  #takes arguments into variable
  password_checkEnc = fernet.encrypt(password.encode())
  inputs = (email, password_checkEnc)
  #executes line 62 to save the data that matches the arguments from 'inputs' and stores in emailList
  cursor.execute(emailList, inputs)
  user = cursor.fetchone()
  #if statement to check if the database holds the data that is being searched for, allowing either the user to login or not
  if user is not None:
    print("login successful")
  else:
    print("incorrect information")

【问题讨论】:

    标签: python sqlite encryption fernet


    【解决方案1】:

    为什么不解密密码并以这种方式检查呢?我对 fernet 密钥加密的理解是完全按照您的描述进行操作,每次都对值进行随机加密。密钥的用途是稍后对其进行解密。查看您最初加密密码的代码可能会有所帮助,但仅查看此处的内容,您似乎正在生成一个新密钥,而不是使用与以前相同的密钥。您必须实际保存您最初创建的密钥,如下所示:

    # key generation
    key = Fernet.generate_key()
    fernet = Fernet(key)
    
    # string the key in a file
    with open('C:/locationofyourchoosing/newkey.key', 'wb') as filekey:
        filekey.write(key)
    
    # using the key to encrypt
    f = Fernet(key)
    f.encrypt(databasepassword)
    
    

    然后您使用相同的密钥稍后像这样解密该值:

    # opening the key
    with open('C:/locationofyourchoosing/newkey.key', 'rb') as filekey:
        key = filekey.read()
    
    f = Fernet(key)
    f.decrypt(databasepassword)
    
    

    然后从那里您可以检查密码的相等性。如果这不是您想要的,请原谅我,但我不确定您每次都能生成相同的加密字符串,因为我认为这会破坏目的。我希望这会有所帮助,如果我完全错过了标记,请告诉我,因为我对您为什么要以这种方式检查相等性感到有点困惑。

    【讨论】:

      猜你喜欢
      • 2014-08-29
      • 2012-03-19
      • 1970-01-01
      • 2015-09-15
      • 2012-04-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多