Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

salt makes everything better #5

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 18 additions & 9 deletions git/auth.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import getpass
import hashlib
import json
import pathlib
import random
Expand Down Expand Up @@ -27,8 +28,10 @@ def get_credentials():
def authenticate(username, pass_text, pwdb):
success = False
if username in pwdb:
pwd, salt = pwdb[username]['pwd'], pwdb[username]['salt']

# calculate hash and compare with stored hash
if pwhash(pass_text) == pwdb[username]:
if pwhash(pass_text, salt) == pwd:
success = True
return success

Expand All @@ -37,7 +40,11 @@ def add_user(username, password, pwdb, pwdb_path):
if username in pwdb:
err(f'Username already exists [{username}]', 2)
else:
pwdb[username] = pwhash(password)
salt = get_salt()
pwdb[username] = {
'pwd': pwhash(password, salt),
'salt': salt
}
write_pwdb(pwdb, pwdb_path)

def read_pwdb(pwdb_path):
Expand All @@ -58,13 +65,15 @@ def write_pwdb(pwdb, pwdb_path):
with open(pwdb_path, 'wt') as pwdb_file:
json.dump(pwdb, pwdb_file)

def pwhash(pass_text):
# simple additive hash -> very insecure!
hash_ = 0
for idx, char in enumerate(pass_text):
# use idx as a multiplier, so that shuffling the characters returns a
# different hash
hash_ += (idx+1)*ord(char)
def get_salt():
# generate a random salt
salt = ''.join(random.choices(string.ascii_letters + string.digits, k=5))
return salt

def pwhash(pass_text, salt):
text = pass_text.encode('utf-8') + salt.encode('utf-8')
# use a secure hash function
hash_ = hashlib.sha256(text).hexdigest()
return hash_

if __name__ == '__main__':
Expand Down