使用来自用户数据库的Python凭据安全登录 [英] Secure login with Python credentials from user database

查看:102
本文介绍了使用来自用户数据库的Python凭据安全登录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我喜欢使用Python创建安全登录名,但是需要从数据库中检查用户表,以便多个用户可以使用自己的密码登录. 主要是这样,就像魅力一样,但是当然不能保证安全.

I like to create a secure login with Python but need to check the user table from a database, so that multiple users can log in with their own password. Mainly like this, works like a charm but not secured of course.

while True:
USER = input("User: ")
PASSWORD = getpass.getpass()

db = sqlite3.connect("test.db")
c = db.cursor()
login = c.execute("SELECT * from LOGIN WHERE USER = ? AND PASSWORD = ?", (USER, PASSWORD))

if (len(login.fetchall()) > 0):
    print()
    print("Welcome")
    break

else:
    print("Login Failed")
    continue

因此,我尝试对密码进行哈希处理,当然也可以使用,但是后来我无法将其存储在数据库中以进行检查,因此根本就没有检查.

So then I tried hashing the password, work also of course, but then I can't store it on the database to check, so there is no check at all.

from passlib.hash import sha256_crypt

password = input("Password: ")
hash1 = sha256_crypt.encrypt( password )
hash2 = sha256_crypt.encrypt( password )
print(hash1)
print(hash2)


import getpass
from passlib.hash import sha256_crypt
passwd = getpass.getpass("Please enter the secret password: ")

if sha256_crypt.verify( passwd, hash ):
print("Everything worked!")

else:
print("Try again :(")

我这样尝试过,以便密码哈希将从数据库中获取,但没有成功:

I tried like this so that the password hash would be taken from the database but with no success:

USER = input("User: ")
db = sqlite3.connect("test.db")
c = db.cursor()
hash = "SELECT HASH FROM LOGIN WHERE USER = %s"%USER
print(hash)
passwd = getpass.getpass("Password: ")

if sha256_crypt.verify( passwd, hash ):
    print("Everything worked!")

else:
    print("Try again :(")

所以我的问题是,为程序创建安全登录名的最佳方法是什么?正如用户表中所述,我确实需要为不同的用户提供不同的登录名.我以前在MySQL上做过,但是出于测试目的,我现在尝试在sql3上做.所以没关系.只要我知道该如何处理.

So my question is, what is the best way to create a secure login for my program? And I do need different logins for different users as stated in the user table. I did it on MySQL before but for testing purpose I'm now trying on sql3. So that doesn't matter. As long as I know how to approach this.

推荐答案

真的,您应该完全避免自己这样做.有很多库可以正确实现这种身份验证.

Really you should avoid doing this yourself at all. There are plenty of libraries that correctly implement this kind of authentication.

不过,遵循的模式是这样的:

Nevertheless, the pattern to follow is like this:

  • 根本不将普通密码存储在数据库中.创建用户帐户后,请立即对密码进行哈希处理并将其存储.
  • 用户登录时,对输入的密码值进行哈希处理,然后将其与已经存储在数据库中的值进行比较.

(请注意,为了获得良好的安全性,您不仅需要使用现代的哈希算法,还应使用

(Note that for decent security, you not only need to use a modern hash algorithm but should also use a salt).

这篇关于使用来自用户数据库的Python凭据安全登录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆