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:
(Note that for decent security, you not only need to use a modern hash algorithm but should also use a salt).