<p>将以下代码视为伪代码。。</p>
<pre><code>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!"
</code></pre>
<p>我建议不要使用逗号分隔的文件,而是使用SQLite3(它可以用于其他设置等)。</p>
<p>另外,请记住,这不是很安全-如果应用程序是本地的,邪恶的用户可能只是替换<code>~/.myauth.txt</code>文件。。本地应用程序身份验证很难做好。您必须使用用户密码加密它读取的任何数据,并且通常要非常小心。</p>