我正在寻找一个python库,它可以帮助我为我正在编写的桌面应用程序创建身份验证方法。我在web框架中发现了几种方法,比如django或turbogears。
我只想要一种用户名-密码关联存储到本地文件中。我可以自己写,但我真的觉得它已经存在了,而且会是一个更好的解决方案(我对加密不是很熟练)。
发布于 2008-09-16 10:08:57
将以下代码视为伪代码。
try:
from hashlib import sha as hasher
except ImportError:
# You could probably exclude the try/except bit,
# but older Python distros dont have hashlib.
try:
import sha as hasher
except ImportError:
import md5 as hasher
def hash_password(password):
"""Returns the hashed version of a string
"""
return hasher.new( str(password) ).hexdigest()
def load_auth_file(path):
"""Loads a comma-seperated file.
Important: make sure the username
doesn't contain any commas!
"""
# Open the file, or return an empty auth list.
try:
f = open(path)
except IOError:
print "Warning: auth file not found"
return {}
ret = {}
for line in f.readlines():
split_line = line.split(",")
if len(split_line) > 2:
print "Warning: Malformed line:"
print split_line
continue # skip it..
else:
username, password = split_line
ret[username] = password
#end if
#end for
return ret
def main():
auth_file = "/home/blah/.myauth.txt"
u = raw_input("Username:")
p = raw_input("Password:") # getpass is probably better..
if auth_file.has_key(u.strip()):
if auth_file[u] == hash_password(p):
# The hash matches the stored one
print "Welcome, sir!"
与使用逗号分隔的文件不同,我建议使用SQLite3 (它可以用于其他设置等。
此外,请记住这不是非常安全-如果应用程序是本地的,恶意用户可能只需替换~/.myauth.txt
文件。本地应用程序身份验证很难做好。您必须使用用户密码对它读取的任何数据进行加密,并且通常要非常小心。
发布于 2008-09-16 09:27:29
发布于 2008-09-16 09:50:35
如果您想要简单,那么使用一个字典,其中键是用户名,值是密码(用SHA256之类的东西加密)。Pickle它到/从磁盘(因为这是一个桌面应用程序,我假设在内存中保持它的开销将可以忽略不计)。
例如:
import pickle
import hashlib
# Load from disk
pwd_file = "mypasswords"
if os.path.exists(pwd_file):
pwds = pickle.load(open(pwd_file, "rb"))
else:
pwds = {}
# Save to disk
pickle.dump(pwds, open(pwd_file, "wb"))
# Add password
pwds[username] = hashlib.sha256(password).hexdigest()
# Check password
if pwds[username] = hashlib.sha256(password).hexdigest():
print "Good"
else:
print "No match"
请注意,这会将密码存储为hash -因此它们本质上是不可恢复的。如果你丢失了你的密码,你会被分配一个新的,而不是找回旧的。
https://stackoverflow.com/questions/70653
复制相似问题