6

我有一个小型 python 程序,将由一小群人(<15 人)在本地使用。但为了问责,我想在程序开始时进行简单的用户名+密码检查(不需要超级安全)。供您参考,我只是一个初学者,这是我第一次尝试它。当我四处搜索时,我发现python有用于加密的passlib。但即使在看了之后,我仍然不确定如何实现我的加密。所以,我想知道一些事情。

  1. 如何在本地存储用户的密码?我目前知道的唯一方法是创建一个文本文件并从中读取/写入,但这会破坏加密的整个目的,因为人们可以打开文本文件并从那里读取它。
  2. 哈希和盐在加密中意味着什么以及它是如何工作的?(一个简短的解释就可以了。)
  3. 实施用户名和密码检查的推荐方法是什么?

我很抱歉这些愚蠢的问题。但如果您能回答我的问题,我将不胜感激。

4

4 回答 4

7
import getpass
import pickle
import hashlib
from os import path

def Encryption(data):
    return hashlib.sha512(data).hexdigest()

## First we check if the database exists.
if path.isfile('database.db'):
    with open('database.db', 'rb') as fh:
        db = pickle.load(fh)

## If it doesn't, we will create one.
else:
    ## First we create the desired variable.
    db = {'torxed' : Encryption('wham'), 'someoneelse' : Encryption('pass')}
    ## Then we open a filehandle to it.
    with open('database.db', 'wb') as fh:
        ## And then we dump the variable into the filehandle.
        ## This will keep the variable intact between sessions,
        ## meaning the next time you start your script, the variable will look the same.
        pickle.dump(db, fh)


## Then we ask the user for his/hers credentials.
user = raw_input('Username: ')
_pass = getpass.getpass('Password: ')

## If the user exists in the "db" and the decoded password
## Matches the logged in user, it's a-ok :)
if user in db and db[user] == Encryption(_pass):
    print('You logged in')

添加更多用户

import pickle, hashlib

def Encryption(data):
    return hashlib.sha512(data).hexdigest()

with open('database.db', 'rb') as fh:
    db = pickle.load(fh)

db['new_user'] = Encryption('password')

with open('database.db', 'wb') as fh:
    pickle.dump(db, fh)

另一种方法是sys.argv在添加用户时从命令行获取用户名和密码,在这种情况下:

import pickle, hashlib, sys
if len(sys.argv) < 3:
    raise ValueError('Need two parameters, username and password')

def Encryption(data):
    return hashlib.sha512(data).hexdigest()

with open('database.db', 'rb') as fh:
    db = pickle.load(fh)

db[sys.argv[1]] = Encryption(sys.argv[2])

with open('database.db', 'wb') as fh:
    pickle.dump(db, fh)

我应该扩展这个答案并解释你也应该加盐密码,而不仅仅是用 SHA 哈希存储它们。

另请注意,当存储在内存中时,密码严格来说是“不安全的”,因为在编写本文时 Python 中没有SecureString ( more )。但出于基本目的,这个答案仍然适用。

于 2013-05-02T09:24:36.210 回答
1

你可以像这样进行散列。

import hashlib
def Encryption(data):
    return hashlib.sha224(data).hexdigest()

当您想保存密码时,请调用此函数并保存编码密码。

于 2013-05-02T09:57:40.887 回答
0

您可以使用Pickle,它是一种将内容序列化为 .pkl 文件的简单方法,该文件很难打开和读取。

于 2013-05-02T16:48:37.787 回答
-1

您可以使用与 apache 一起安装的 htpasswd,也可以单独下载。使用 subprocess.check_output 运行它,您可以创建 Python 函数来添加用户、删除用户、验证他们是否提供了正确的密码等。传递 -B 选项以启用加盐,您将知道它是安全的(与实现加盐不同你自己)。

于 2013-05-02T09:40:31.317 回答