我正在寻找一个Python库,可以帮助我为我正在编写的桌面应用程序创建身份验证方法。在Web框架(如Django或TurboGears)中,我已经找到了几种方法。
我只需要将用户名和密码关联存储到本地文件中即可。我可以自己编写,但我真的很希望它已经存在并且是更好的解决方案(我对加密不太精通)。
def hash_password(password):
"""Returns the hashed version of a string
"""
return hasher.new( str(password) ).hexdigest()
这是一种非常不安全的密码哈希方式。你不应该这样做。如果想知道为什么,请阅读OpenBSD密码哈希系统的作者写的Bycrypt Paper。此外,如果想了解有关如何破解密码的讨论,请查看Jack the Ripper的作者的这次采访。
现在,B-Crypt很棒,但我必须承认我没有使用这个系统,因为我没有可用的EKS-Blowfish算法,也不想自己实现它。我使用稍微更新的FreeBSD系统,下面将发布其代码。要点是:不要仅仅对密码进行哈希。对密码进行加盐,然后哈希密码并重复10,000次左右。
如果这不太清楚,以下是代码:
#note I am using the Python Cryptography Toolkit
from Crypto.Hash import SHA256
HASH_REPS = 50000
def __saltedhash(string, salt):
sha256 = SHA256.new()
sha256.update(string)
sha256.update(salt)
for x in xrange(HASH_REPS):
sha256.update(sha256.digest())
if x % 10: sha256.update(salt)
return sha256
def saltedhash_bin(string, salt):
"""returns the hash in binary format"""
return __saltedhash(string, salt).digest()
def saltedhash_hex(string, salt):
"""returns the hash in hex format"""
return __saltedhash(string, salt).hexdigest()
import hashlib
import random
def gen_salt():
salt_seed = str(random.getrandbits(128))
salt = hashlib.sha256(salt_seed).hexdigest()
return salt
def hash_password(password, salt):
h = hashlib.sha256()
h.update(salt)
h.update(password)
return h.hexdigest()
#in datastore
password_stored_hash = "41e2282a9c18a6c051a0636d369ad2d4727f8c70f7ddeebd11e6f49d9e6ba13c"
salt_stored = "fcc64c0c2bc30156f79c9bdcabfadcd71030775823cb993f11a4e6b01f9632c3"
password_supplied = 'password'
password_supplied_hash = hash_password(password_supplied, salt_stored)
authenticated = (password_supplied_hash == password_stored_hash)
print authenticated #True
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"
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而不是使用逗号分隔的文件(SQLite3也可以用于其他设置等)。
此外,请记住这并不是非常安全的 - 如果应用程序是本地的,那么恶意用户可能只需替换~/.myauth.txt
文件即可。本地应用程序认证很难做好。您将不得不使用用户密码加密它读取的任何数据,并且通常要非常小心。
使用 "md5" 比 base64 更好。
>>> import md5
>>> hh = md5.new()
>>> hh.update('anoop')
>>> hh.digest
<built-in method digest of _hashlib.HASH object at 0x01FE1E40>