密码保护Python

Chr*_*ung 3 python encryption passwords

我有一个小的python程序,将由一小群人(<15人)在本地使用.但是为了问责制,我希望在程序开始时使用简单的用户名+密码检查(不需要对于你的信息,我只是一个初学者,这是我第一次尝试它.当我搜索时,我发现python有passlib加密.但即使看了之后,我仍然不确定如何实现我的加密.所以,我想知道一些事情.

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

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

Tor*_*xed 5

import getpass
import pickle
import hashlib
from os import path

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

## First we check if the database exists.
if path.isfile('database.db'):
    fh = open('database.db', 'rb')
    db = pickle.load(fh)
    fh.close()
## 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.
    fh = open('database.db', 'wb')
    ## 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)
    fh.close()


## 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'
Run Code Online (Sandbox Code Playgroud)

添加更多用户

import pickle, hashlib

def Encryption(data):
    return hashlib.sha224(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)
Run Code Online (Sandbox Code Playgroud)

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

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

def Encryption(data):
    return hashlib.sha224(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)
Run Code Online (Sandbox Code Playgroud)