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 :(")

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:

Don't store the plain password in the database at all. When the user account is created, hash the password immediately and store that.

When the user logs in, hash the value they enter for the password, then compare that against the value stored in the database already.

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值