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 )がないため、メモリに格納されている場合、パスワードは厳密に言えば「安全ではない」ことに注意してください。しかし、基本的な目的のために、この答えはまだ適用されます。