Python身份验证API

6
我正在寻找一个Python库,可以帮助我为我正在编写的桌面应用程序创建身份验证方法。在Web框架(如Django或TurboGears)中,我已经找到了几种方法。 我只需要将用户名和密码关联存储到本地文件中即可。我可以自己编写,但我真的很希望它已经存在并且是更好的解决方案(我对加密不太精通)。
6个回答

11
dbr说:
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()

部署此类系统的关键是考虑 HASH_REPS 常量。这是该系统中可扩展的成本因素。您需要进行测试以确定每个哈希计算所需等待时间与密码文件基于离线字典攻击的风险之间的可接受差距。
安全很难,我介绍的方法并不是做到这一点的最佳方法,但它比简单哈希好得多。此外,它极易实现。因此,即使您没有选择更复杂的解决方案,也不是最糟糕的选择。
希望这可以帮助您, 蒂姆

3
我认为你应该制定自己的身份验证方法,因为这样可以最好地适应你的应用程序,但是在加密方面使用库,比如pycrypto或其他更轻量级的库。
另外,如果你需要pycrypto的Windows二进制文件,可以在这里获取。

感谢提供关于pycripto的链接。它将有助于轻松创建加密过程,这并不是我最喜欢的部分。 - Bertrand

0
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

参见GAE授权给第三方网站


0
如果您想要简单的话,可以使用一个字典,其中键是用户名,值是密码(使用类似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"

请注意,此代码将密码存储为哈希值 - 因此它们基本上是不可恢复的。如果您忘记了密码,您将被分配一个新密码,而不是找回旧密码。

0
请把以下内容视为伪代码。
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文件即可。本地应用程序认证很难做好。您将不得不使用用户密码加密它读取的任何数据,并且通常要非常小心。


1
这是非常不安全的。根本不建议使用。 - Kiarash

-1

使用 "md5" 比 base64 更好。

>>> import md5
>>> hh = md5.new()
>>> hh.update('anoop')
>>> hh.digest
<built-in method digest of _hashlib.HASH object at 0x01FE1E40>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接