首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >Python身份验证API

Python身份验证API
EN

Stack Overflow用户
提问于 2008-09-16 09:17:41
回答 5查看 10.2K关注 0票数 6

我正在寻找一个python库,它可以帮助我为我正在编写的桌面应用程序创建身份验证方法。我在web框架中发现了几种方法,比如django或turbogears。

我只想要一种用户名-密码关联存储到本地文件中。我可以自己写,但我真的觉得它已经存在了,而且会是一个更好的解决方案(我对加密不是很熟练)。

EN

回答 5

Stack Overflow用户

回答已采纳

发布于 2008-09-16 10:08:57

将以下代码视为伪代码。

代码语言:javascript
复制
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文件。本地应用程序身份验证很难做好。您必须使用用户密码对它读取的任何数据进行加密,并且通常要非常小心。

票数 0
EN

Stack Overflow用户

发布于 2008-09-16 09:27:29

我认为您应该制定自己的身份验证方法,因为您可以让它最适合您的应用程序,但是使用一个库进行加密,比如pycrypto或其他一些更轻量级的库。

顺便说一句,如果你需要用于pycrypto的windows二进制文件,你可以得到here

票数 3
EN

Stack Overflow用户

发布于 2008-09-16 09:50:35

如果您想要简单,那么使用一个字典,其中键是用户名,值是密码(用SHA256之类的东西加密)。Pickle它到/从磁盘(因为这是一个桌面应用程序,我假设在内存中保持它的开销将可以忽略不计)。

例如:

代码语言:javascript
复制
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 -因此它们本质上是不可恢复的。如果你丢失了你的密码,你会被分配一个新的,而不是找回旧的。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70653

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档