HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonMinor

Storing hashed passwords

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
storingpasswordshashed

Problem

I'm a beginner and am self taught and was hoping I could get help from others more educated than me to show me what bad practices I might be forming before I go on further.

P.S. This program is just for me to learn, I'm not actually storing passwords with it.

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys

def openPassFile():
    try:
        passwordFile = open('hashwork.txt', 'a')
        return passwordFile
    except IOError as e:
        print("I/O Error({0}): {1}".format(e.errno, e.strerror))
        quit

def closePassFile(passwordFile):
    try:
        passwordFile.close()
    except IOError as e:
        print("I/O Error({0}): {1}".format(e.errno, e.strerror))
        quit

def randomValue(length):
    import random
    salt_chars = 'abcdefghijklmnopqrstuvwxyz0123456789'
    return ''.join(random.choice(salt_chars) for x in range(length))

def askforUsername():
    while True:
        print("Please enter the username you would like to use:")
        username = raw_input()
        return username

def askforPassword():
    import getpass, hashlib
    while True:
        print("What password would you like to create?")
        salt = randomValue(16)
        hashedPassword1 = hashlib.sha256(salt+getpass.getpass()).hexdigest()
        print("\nPlease enter password again.")
        hashedPassword2 = hashlib.sha256(salt+getpass.getpass()).hexdigest()
        if hashedPassword1 == hashedPassword2:
            return hashedPassword2, salt
            break
        else:
            print("Your passwords do not match. Please retry")

def storeInfo(username, hashedPass, salt):
    passwordFile = openPassFile()
    passwordFile.write(username + " | " + hashedPass + " | " + salt + "\n")
    closePassFile(passwordFile)

username = askforUsername()         
hashedPass, salt = askforPassword()
storeInfo(username, hashedPass, salt)
sys.exit()

Solution


  • SHA256 is not a secure password hash because it is fast. See How to securely hash passwords? on security.se for details.



  • It's not obvious that random is good enough to generate salts. While the requirments for salts are lower than those for keys, you still need a decent RNG. I recommend using SystemRandom.

Context

StackExchange Code Review Q#127430, answer score: 5

Revisions (0)

No revisions yet.