PythonIntermediate · Windows, macOS, or Linux; Python 3.12+

Create or verify a password hash record

Use PBKDF2-HMAC-SHA256 with a random salt and an interactive password prompt to create or verify a local record.

Before you begin

  • Python 3.12 or later.
  • An interactive terminal. This illustrates local password verification; integrating application authentication requires more design.
What this script changesCreates one new record or reads a record in verify mode; refuses overwrite. Passwords are entered through getpass, not command-line arguments. Hash records still need protection.

Set up your example

  1. Save as security-password-hash-record.py.
  2. Open a terminal in its folder.
  3. Run python "security-password-hash-record.py" --help and prepare the listed input files.

This recipe uses your own local input or creates its own example output. Follow the setup steps below.

Download the ZIP, extract it, and open a terminal inside the extracted folder. The source file is security-password-hash-record.py.

Run the script

Run command
python "security-password-hash-record.py" "password-record.json"

If your system uses python3 instead of python, use that command for Python examples. Keep paths containing spaces in quotes. Required inputs and optional settings are described in the code and setup steps.

What to expect

Two matching hidden prompts create a new hash record; --verify checks a later hidden prompt.

The complete script

security-password-hash-record.py
#!/usr/bin/env python3
"""Use PBKDF2-HMAC-SHA256 with a random salt and an interactive password prompt to create or verify a local record."""
import argparse
import sys
import json
from pathlib import Path
import getpass
import secrets
import hashlib
import hmac

def main():
    parser = argparse.ArgumentParser(description='Use PBKDF2-HMAC-SHA256 with a random salt and an interactive password prompt to create or verify a local record.')
    parser.add_argument('record',type=Path)
    parser.add_argument('--verify',action='store_true')
    args = parser.parse_args()
    password=getpass.getpass('Password (input hidden): ').encode('utf-8')
    if args.verify:
        row=json.loads(args.record.read_text(encoding='utf-8'));iterations=int(row['iterations'])
        if not 100000<=iterations<=5000000:raise ValueError('Unreasonable iteration count')
        salt=bytes.fromhex(row['salt']);expected=bytes.fromhex(row['digest'])
        if len(salt)!=16 or len(expected)!=32:raise ValueError('Invalid record lengths')
        actual=hashlib.pbkdf2_hmac('sha256',password,salt,iterations)
        print('MATCH' if hmac.compare_digest(actual,expected) else 'NO MATCH')
    else:
        confirmation=getpass.getpass('Confirm password: ').encode('utf-8')
        if not hmac.compare_digest(password,confirmation):raise ValueError('Passwords do not match')
        salt=secrets.token_bytes(16);iterations=600000
        digest=hashlib.pbkdf2_hmac('sha256',password,salt,iterations)
        with args.record.open('x',encoding='utf-8') as out:json.dump({'algorithm':'pbkdf2-sha256','iterations':iterations,'salt':salt.hex(),'digest':digest.hex()},out,indent=2)
        print(f'Created {args.record}; keep this record private.')

if __name__ == '__main__':
    try:
        main()
    except (OSError, ValueError, RuntimeError) as exc:
        print(f'Error: {exc}', file=sys.stderr)
        sys.exit(1)

Open source as plain text · Download source and sample files

How it works

  1. Use PBKDF2-HMAC-SHA256 with a random salt and an interactive password prompt to create or verify a local record.
  2. Arguments are explicit and expected input errors produce a message with a nonzero exit code.
  3. Results reflect your selected local data or the specific endpoint you choose; the example illustrates the result shape.

Make it your own

Adapt the task

Use --verify with an existing record. Tune iterations only after measuring your environment and consulting your application security requirements.

Adjust presentation

Edit final print statements or json.dumps indentation to adjust the report layout. Keep input validation and exclusive-create file modes intact.

Change one setting at a time, run it again on sample data, and compare the output. The customization guide walks through this process.

If something goes wrong

An input or dependency is unavailable.

An interactive terminal. This illustrates local password verification; integrating application authentication requires more design.

Actual results differ from the example.

Inputs and system state determine values. Review each finding in context; a report is not proof of system health or a complete security assessment.

Reference & next steps

These official references explain the underlying tools. The Scriptage example and guide are original instructional content. See verification notes for what has been checked and the limits of those checks.

Copies a template for your own notes. It does not send anything.