Skip to content

Authentication & Cryptography

Secure Password Storage: Best Practices with Modern Hashing Algorithms

A comprehensive guide to modern password hashing techniques and implementation best practices

By Deepak Gupta·November 18, 2024·5 min read

Key Findings

  • Modern password hashing algorithms like Argon2, bcrypt, and scrypt provide essential defenses against brute-force and dictionary attacks
  • Proper implementation requires careful tuning of cost parameters, salt generation, and memory usage to balance security with performance
  • Compliance frameworks increasingly mandate the use of adaptive hashing functions over legacy algorithms for credential storage
password hashingsecure storageargon2bcryptscryptcryptographyauthentication

Understanding Password Storage Fundamentals

The Evolution of Password Storage

  • Plain text storage (historically)
  • Simple hashing (MD5, SHA-1)
  • Salted hashes
  • Modern adaptive hashing functions

Key Concepts

What Makes Password Storage Secure?

  1. One-way transformation: Impossible to reverse the hash to obtain the original password
  2. Uniqueness: Different passwords should produce different hashes
  3. Avalanche effect: Small changes in input create significant changes in output
  4. Computational intensity: Resistance to brute-force attacks

The Role of Salt

A salt is a random value that is:

  • Unique for each user
  • At least 16 bytes in length
  • Generated using a cryptographically secure random number generator
  • Stored alongside the password hash
import os
import hashlib

def generate_salt():
    return os.urandom(16)  # Generate a 16-byte random salt

Modern Password Hashing Algorithms

Comparison of Modern Algorithms

Argon2

Winner of the Password Hashing Competition (PHC)

from argon2 import PasswordHasher

ph = PasswordHasher(
    time_cost=2,      # Number of iterations
    memory_cost=65536, # Memory usage in KiB
    parallelism=4,    # Number of parallel threads
    hash_len=32,      # Length of the hash in bytes
    salt_len=16       # Length of the salt in bytes
)

hash = ph.hash("user_password")

Key Parameters:

  • memory_cost: Amount of memory required
  • time_cost: Number of iterations
  • parallelism: Degree of parallelization
  • hash_len: Length of the hash
  • salt_len: Length of the salt

bcrypt

Industry Standard Since 1999

import bcrypt

def hash_password(password):
    salt = bcrypt.gensalt(rounds=12)  # Work factor of 2^12
    return bcrypt.hashpw(password.encode(), salt)

Key Features:

  • Built-in salt generation
  • Configurable work factor
  • Memory-hard function
  • Wide platform support

scrypt

Memory-Hard Algorithm

import hashlib
import os

def hash_password_scrypt(password):
    salt = os.urandom(16)
    return hashlib.scrypt(
        password.encode(),
        salt=salt,
        n=2**14,      # CPU/memory cost
        r=8,          # Block size
        p=1,          # Parallelization
        maxmem=2**25  # 32 MB
    )

Algorithm Selection Guide

Algorithm Memory Cost CPU Cost Parallelism Best Use Case
Argon2id High Medium Yes General purpose, high-security systems
bcrypt Medium High No Legacy systems, wide compatibility
scrypt High Medium Limited Memory-constrained environments

Implementation Best Practices

1. Proper Salt Management

def create_hash_with_salt(password):
    salt = generate_salt()
    # Store both salt and hash
    return {
        'salt': salt.hex(),
        'hash': hash_function(password, salt).hex()
    }

2. Secure Parameter Selection

# Argon2 recommended parameters for different scenarios
ARGON2_PARAMETERS = {
    'high_security': {
        'time_cost': 4,
        'memory_cost': 131072,  # 128 MB
        'parallelism': 4
    },
    'web_application': {
        'time_cost': 2,
        'memory_cost': 65536,   # 64 MB
        'parallelism': 2
    },
    'resource_constrained': {
        'time_cost': 1,
        'memory_cost': 32768,   # 32 MB
        'parallelism': 1
    }
}

3. Hash Verification

def verify_password(stored_password_data, provided_password):
    try:
        salt = bytes.fromhex(stored_password_data['salt'])
        stored_hash = bytes.fromhex(stored_password_data['hash'])
        calculated_hash = hash_function(provided_password, salt)
        return hmac.compare_digest(stored_hash, calculated_hash)
    except Exception:
        return False

Common Vulnerabilities and Mitigation

1. Rainbow Table Attacks

Mitigation: Proper salt implementation and modern algorithms

2. Timing Attacks

# Use constant-time comparison
from hmac import compare_digest

def secure_compare(a, b):
    return compare_digest(a, b)

3. Brute Force Protection

from datetime import datetime, timedelta

class LoginAttemptTracker:
    def __init__(self, max_attempts=5, lockout_period=timedelta(minutes=15)):
        self.attempts = {}
        self.max_attempts = max_attempts
        self.lockout_period = lockout_period

    def is_locked_out(self, user_id):
        if user_id not in self.attempts:
            return False
        
        attempts = self.attempts[user_id]
        if len(attempts) < self.max_attempts:
            return False
            
        latest_attempts = sorted(attempts)[-self.max_attempts:]
        oldest_recent_attempt = latest_attempts[0]
        return datetime.now() - oldest_recent_attempt < self.lockout_period

    def record_attempt(self, user_id):
        if user_id not in self.attempts:
            self.attempts[user_id] = []
        self.attempts[user_id].append(datetime.now())

Performance Considerations

Benchmarking Different Algorithms

import time
import statistics

def benchmark_hash_function(hash_func, iterations=100):
    times = []
    for _ in range(iterations):
        start = time.perf_counter()
        hash_func("test_password")
        end = time.perf_counter()
        times.append(end - start)
    
    return {
        'mean': statistics.mean(times),
        'median': statistics.median(times),
        'std_dev': statistics.stdev(times)
    }

Optimal Parameter Selection

  • Target hashing time: 250ms for authentication
  • Scale parameters based on server capabilities
  • Regular benchmark testing

Migration Strategies

Gradual Password Rehashing

def migrate_password_hash(old_hash_data, new_hash_function):
    def wrapper(password):
        # Verify with old hash
        if verify_old_hash(old_hash_data, password):
            # Generate new hash
            new_hash = new_hash_function(password)
            # Return new hash and migration flag
            return new_hash, True
        return None, False
    return wrapper

Version Tracking

class PasswordHashData:
    def __init__(self, version, salt, hash):
        self.version = version
        self.salt = salt
        self.hash = hash

    def to_dict(self):
        return {
            'version': self.version,
            'salt': self.salt.hex(),
            'hash': self.hash.hex()
        }

    @classmethod
    def from_dict(cls, data):
        return cls(
            version=data['version'],
            salt=bytes.fromhex(data['salt']),
            hash=bytes.fromhex(data['hash'])
        )

Compliance and Regulatory Requirements

NIST Guidelines (SP 800-63B)

  • Minimum length: 8 characters
  • Maximum length: At least 64 characters
  • Allow all ASCII characters
  • Implement rate limiting
  • Use approved algorithms (Argon2, PBKDF2, scrypt, bcrypt)

GDPR Considerations

  • Implement appropriate technical measures
  • Document hashing procedures
  • Regular security assessments
  • Incident response planning

Conclusion

Secure password storage is a critical component of application security. By following these best practices:

  1. Use modern hashing algorithms (preferably Argon2id)
  2. Implement proper salting
  3. Choose appropriate work factors
  4. Regular security audits
  5. Plan for algorithm migration
  6. Monitor performance impacts
  7. Follow compliance requirements

You can create a robust password storage system that protects your users' credentials while maintaining system performance and usability.

References

  1. NIST Special Publication 800-63B
  2. Password Hashing Competition (PHC)
  3. OWASP Password Storage Cheat Sheet
  4. The Open Web Application Security Project (OWASP)
  5. Cryptographic Standards and Guidelines (NIST)

More Research

Independent research and analysis from 15+ years of building in cybersecurity, AI, and SaaS

Cybersecurity Foundations

The AI Security Stack of 2026: Governance, Red Teaming, MLSecOps, Threat Detection, and Agentic Defense

How the five layers of AI security actually fit together — and what to build first

13 minRead →

Cybersecurity Foundations

Application Security 101: SAST, DAST, IAST, ASPM, SCA, and the Modern AppSec Stack

How the application security toolchain actually fits together, what each acronym does, and where to start

16 minRead →

Frontier AI Models

Grok AI Explained: xAI's Model Family, Capabilities, and Where It Fits

How Grok works, what makes it different from ChatGPT and Claude, and what it is actually good at

11 minRead →

AI Infrastructure & Hardware

NPU Explained: What a Neural Processing Unit Is, How It Differs From a CPU and GPU

How NPUs work, why every laptop and phone now has one, and what they actually accelerate

12 minRead →

Cybersecurity Foundations

Zero Trust Architecture Explained: SASE, SSE, ZTNA, and How the Pieces Actually Fit

The vendor-neutral guide to Zero Trust: what NIST 800-207 actually says, how SASE and SSE differ, where ZTNA fits, and what to build first

17 minRead →

Industry Research & Market Analysis

AI Receptionists for SMBs: Market Data, ROI, and Implementation Guide

How AI Receptionists Are Rewiring SMB Communication with 75% Fewer Missed Calls and 300% First-Year ROI

20 minRead →

Industry Research & Market Analysis

Generative Engine Optimization (GEO): Market Research & Industry Analysis 2026

A Deep Analysis of Monitoring & Content Platforms, Market Gaps, and Strategic Opportunities

25 minRead →

Industry Research & Market Analysis

CIAM Industry Research Report: M&A and Investment Analysis

Comprehensive Market Intelligence for Private Equity, Growth Equity, and Venture Capital Firms

35 minRead →

Industry Insights & Analysis

California's DROP: The First-of-Its-Kind Data Deletion Platform That Could Reshape Global Privacy Standards

How California's DELETE Act and DROP platform are transforming data privacy enforcement

14 minRead →

Authentication & Cryptography

The Complete Guide to Password Hashing: Argon2 vs Bcrypt vs Scrypt vs PBKDF2 (2026)

Benchmarking and comparing modern password hashing algorithms for secure credential storage

25 minRead →

Technical Implementation Guides

Model Context Protocol (MCP): Enterprise Adoption, Market Trends & Implementation

The Complete Guide to MCP, Architecture, Security, Authentication, and Strategic Deployment for Enterprises

35 minRead →

Strategic Frameworks & Playbooks

How Companies Can Achieve AEO and GEO: The Complete 2025 Guide

Optimizing content for AI search visibility through AEO and GEO strategies

18 minRead →

Industry Research & Market Analysis

The Complete Guide to AI-Powered Visual Content Creation

Comprehensive Analysis of AI Image Editing, Generation, and Restoration Platforms Serving 50M+ Creators

30 minRead →

Strategic Frameworks & Playbooks

The Complete Guide to Setting up your US Tech Startup

Foundational decisions for entity selection, banking, payments, and compliance

13 minRead →

Industry Research & Market Analysis

AI Voiceover & Text-to-Speech: A Comprehensive Analysis

Technology, Use Cases, and Market Landscape for AI Voice Synthesis in 2025

25 minRead →

Industry Research & Market Analysis

AI Chat with PDF: Complete Guide & Top Tools

Comprehensive Analysis of the AI Document Interaction Market, Leading Platforms, and Industry Applications

30 minRead →

Industry Insights & Analysis

How Model Context Protocol Servers Facilitate Real-Time Decision Making in AI

Understanding MCP servers' role in enabling AI systems to access live data for instantaneous decisions

6 minRead →

Buyer's Guides & Solution Comparisons

CIAM Security Buyers' Guide 2025: 25 Essential Solutions

Essential Capabilities for Securing Customer Identity and Access Management

30 minRead →

Buyer's Guides & Solution Comparisons

Know Your Customer (KYC) Buyers' Guide 2025

25 Essential Solutions for Customer Verification and Compliance

30 minRead →

Buyer's Guides & Solution Comparisons

Privileged Access Management (PAM) Buyers' Guide 2025

25 Essential Tools for Privileged Access Security

30 minRead →

Buyer's Guides & Solution Comparisons

Workplace Identity & Access Management (IAM) Buyers' Guide 2025

25 Essential IAM Tools and Strategies to Strengthen Your Security Posture

30 minRead →

Authentication & Cryptography

The Future of Hashing: Quantum Resistance and Beyond

How cryptographic hashing must evolve to withstand quantum computing threats

22 minRead →

Authentication & Cryptography

Data Integrity Verification: Implementing Checksums and Hash Verification

Practical guide to implementing checksums and hash verification for data integrity

20 minRead →

Industry Insights & Analysis

Akamai's Identity Cloud Shutdown: The Migration Crisis That's Reshaping Enterprise Authentication

How 1,000+ enterprises face forced migration from Akamai's Identity Cloud

13 minRead →

Buyer's Guides & Solution Comparisons

Best IAM Solutions 2025: Complete Buyer's Guide

Navigating the $24+ billion IAM market with a comparison of 29 leading identity solutions

30 minRead →

Strategic Frameworks & Playbooks

AI Marketing Strategy for B2B SaaS: Expert Implementation

Strategic guide to AI-powered marketing intelligence for B2B SaaS companies

14 minRead →

Strategic Frameworks & Playbooks

The AI Revolution Toolkit: Strategic Framework for Building AI-Powered B2B SaaS Solutions

Frameworks for evaluating and integrating AI across B2B SaaS operations

14 minRead →

Strategic Frameworks & Playbooks

Essential DevOps Tools for B2B SaaS: Founder's Guide

A curated guide to the tools that power modern B2B SaaS infrastructure

9 minRead →

Strategic Frameworks & Playbooks

Building Enterprise Cybersecurity: A Strategic Guide to Security Categories for B2B SaaS

Essential security categories for competing in enterprise B2B SaaS markets

13 minRead →

Buyer's Guides & Solution Comparisons

Comprehensive CIAM Providers Directory: Top Identity Authentication Solutions

Expert analysis of 30+ CIAM solutions across six provider categories

35 minRead →

Strategic Frameworks & Playbooks

Enterprise CIAM Strategy Guide: Implementation & ROI Framework

Implementation frameworks, vendor evaluation, and ROI analysis for enterprise CIAM

13 minRead →

AI Deep Dives

The Complete Guide to Grok AI: Applications, Technical Analysis, and Implementation for Business Leaders

Everything business leaders need to evaluate and implement Grok AI

20 minRead →

AI Deep Dives

Grok AI - Core Concepts, Capabilities, Technical Foundation

Understanding Grok AI's architecture, training methodology, and distinctive capabilities

30 minRead →

AI Deep Dives

Grok 3 Architecture: How It Works Under the Hood

Deep-dive into Grok AI's transformer architecture, benchmarks, and engineering insights

28 minRead →

AI Deep Dives

Grok 3 vs ChatGPT vs Claude, Which AI Wins in 2026?

Comprehensive comparison of leading LLMs across performance, safety, and cost

19 minRead →

Authentication & Cryptography

bcrypt, scrypt, and Argon2: Choosing the Right Password Hashing Algorithm

A comparative analysis of leading password hashing algorithms for different security requirements

22 minRead →

Authentication & Cryptography

BLAKE2 & BLAKE3: Fast & Secure Hashing Options

High-performance hashing alternatives to traditional algorithms like SHA-2 and SHA-3

20 minRead →

Technical Implementation Guides

CIAM 101: A Practical Guide to Customer Identity and Access Management in 2025

From basic authentication to intelligent identity platforms

25 minRead →

Technical Implementation Guides

CIAM Implementation Guide: 5 Key Components & Best Practices 2025

Essential components and configuration for scalable identity solutions

30 minRead →

Technical Implementation Guides

CIAM Performance Optimization and Scalability Guide

Enterprise-scale authentication optimization for millions of users

26 minRead →

Technical Implementation Guides

CIAM Security Best Practices & Templates Guide 2025 | Implementation

Enterprise-grade security controls and implementation templates for CIAM systems

28 minRead →

Authentication & Cryptography

MD5: Understanding its Uses, Vulnerabilities, and Why It's Still Around

Examining MD5's cryptographic weaknesses and its persistent role in non-security applications

20 minRead →

Authentication & Cryptography

SHA-2 Family: Choosing Between SHA-256, SHA-384, and SHA-512

Analyzing the architectural differences, performance trade-offs, and use cases of SHA-2 variants

22 minRead →

Authentication & Cryptography

Passwordless Authentication Implementation Checklist

A structured approach to transitioning from passwords to passwordless authentication

18 minRead →

Buyer's Guides & Solution Comparisons

Passwordless Authentication Solution Selection Matrix

A comparative framework for evaluating passwordless authentication methods across organizational needs

15 minRead →