Python身份验证API

前端之家收集整理的这篇文章主要介绍了Python身份验证API前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在寻找一个 python库,它将帮助我为我正在编写的桌面应用程序创建一个身份验证方法.
我在web框架中找到了几种方法,如django或turbogears.

我只想要一种存储在本地文件中的用户名 – 密码关联.
我可以自己写,但我真的它已经存在并且将是一个更好的解决方案(我对加密不是很流利).

解决方法

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

原文链接:https://www.f2er.com/python/186511.html

猜你在找的Python相关文章