Blog | G5 Cyber Security

Secure Password Storage in Text Files

TL;DR

Storing passwords directly in text files is highly insecure. This guide explains why and provides the *least bad* options if you absolutely must do it, focusing on hashing and salting. However, using a dedicated password manager or secure vault is strongly recommended.

Why Storing Passwords in Text Files is Bad

Plain text passwords are easily readable if the file is compromised (e.g., hacked, accidentally shared). Even with file permissions set correctly, it’s a significant risk.

The Least Worst Approach: Hashing and Salting

Hashing transforms a password into an irreversible string of characters. Salting adds a random value to each password before hashing, making rainbow table attacks much harder. Here’s how:

  1. Choose a Strong Hashing Algorithm: Use bcrypt, scrypt, or Argon2. These are designed for password storage and are slow (which is good – it makes brute-force attacks slower). Do not use MD5 or SHA1; they’re outdated and easily cracked.
  2. Generate Salts: Each password needs a unique salt. A salt should be at least 16 bytes long, randomly generated.
  3. Hash with Salt: Combine the salt and password before hashing.
  4. Store Salt and Hash: Store both the salt and the hash in your text file, separated by a delimiter (e.g., a colon). Never store the original password!

Example using Python

This example uses the bcrypt library. You’ll need to install it first: pip install bcrypt.

import bcrypt

def hash_password(password):
    salt = bcrypt.gensalt()
    hashed_password = bcrypt.hashpw(password.encode('utf-8'), salt)
    return salt, hashed_password.decode('utf-8')

def verify_password(password, stored_hash, stored_salt):
    hashed_password = bcrypt.hashpw(password.encode('utf-8'), stored_salt.encode('utf-8'))
    return hashed_password == stored_hash.encode('utf-8')

# Example Usage
pw = "mySecretPassword"
salt, hash = hash_password(pw)
print(f"Salt: {salt}")
print(f"Hash: {hash}")

# To verify:
if verify_password(pw, hash, salt):
    print("Password verified!")
else:
    print("Incorrect password.")

File Format

Your text file should look like this (one password per line):

salt1:hash1
salt2:hash2
salt3:hash3

Important Considerations

Alternatives (Strongly Recommended)

Exit mobile version