/bcrypt

bcrypt

Créé en 1999 par Provos & MazièresBlowfish-based

Sécurisé - Référence Mots de PasseKey DerivationCost Factor
892,341+
Analyses effectuées

🔑 RÉFÉRENCE ABSOLUE - PROTECTION MOTS DE PASSE

bcrypt est LA référence pour le hachage sécurisé de mots de passe depuis 25 ans. Cost factor adaptatif, résistance éprouvée aux attaques modernes, adoption universelle.

Spécifications Techniques

Nom completBlowfish-based crypt
CréateursNiels Provos, David Mazières
Année1999
BaseBlowfish cipher
Facteur coût4-31 (recommandé 12+)
Sel128 bits (22 chars base64)
Sortie184 bits (31 chars base64)
Statut 2024🟢 SÉCURISÉ

Format de Sortie

$2b$12$R9h/cIPz0gi.URNNX3kh2OUBS6kc6rYOQ3r/g2ujWx9LnPKJKILDY
$2b$ : Version bcrypt
12 : Cost factor (2^12 = 4096 rounds)
R9h/cIPz0gi.URNNX3kh2O : Salt (22 chars)
UBS6kc6rYOQ3r/g2ujWx9LnPKJKILDY : Hash (31 chars)

Analyse Cost Factor (Recommandations 2024)

RoundsTempsUsage RecommandéSécurité
4~1msTests unitaires uniquementFaible
8~16msDéveloppement localInsuffisant
10~64msApplications legacyMinimum
12~256msProduction recommandée 2024Excellent
14~1sHaute sécuritéMaximum
16~4sUltra sécurisé (coûteux)Extreme
Recommandation 2024

Utilisez rounds=12 minimum pour la production. Ce réglage offre le meilleur équilibre sécurité/performance (~250ms par hash) et résiste aux attaques GPU modernes.

Avantages Sécuritaires

Résistance Force Brute

Critique

Cost factor adaptatif ralentit exponentiellement les attaques

Salting Automatique

Essentiel

Sel unique intégré, élimine les rainbow tables

Temps Constant

Important

Protection contre les timing attacks

Évolutivité

Futur-proof

Ajustement du coût selon la puissance hardware

Protection Multi-Niveaux

🛡️ Contre les Attaques
  • • Rainbow tables : Impossible (sel unique)
  • • Force brute : Ralentie exponentiellement
  • • Timing attacks : Temps constant
  • • GPU/ASIC : Cost factor adaptatif
⚡ Optimisations
  • • Évolutivité : Ajustement coût possible
  • • Parallélisation : Support multi-thread
  • • Compatibilité : Implémentations universelles
  • • Monitoring : Métriques performance intégrées

Cas d'Usage Production

Applications Web

Authentification utilisateurs
APIs RESTful/GraphQL
Sessions sécurisées
Réinitialisation mots de passe
2FA backup codes

Systèmes Backend

Microservices auth
Bases de données utilisateurs
LDAP/Active Directory
Configuration system accounts
Service-to-service auth

Infrastructure

Docker containers
Kubernetes secrets
CI/CD pipelines
Configuration management
Backup encryption keys
Adoption Industrielle
Rails
Ruby framework
Django
Python framework
Laravel
PHP framework
Express
Node.js ecosystem

Implémentations Production

Code Production-Ready

Ces exemples incluent toutes les bonnes pratiques : gestion d'erreurs, validation, monitoring, et sécurité avancée pour usage en production.

Node.js - Production Complete

const bcrypt = require('bcrypt');

// Configuration recommandée 2024
const SALT_ROUNDS = 12; // Minimum sécurisé

async function hashPassword(plainPassword) {
  try {
    // Hash avec salt automatique
    const hash = await bcrypt.hash(plainPassword, SALT_ROUNDS);
    return hash;
    // Exemple sortie: $2b$12$LQv3c1yqBWVHxkd0LHAkCO...
  } catch (error) {
    throw new Error('Erreur hachage: ' + error.message);
  }
}

async function verifyPassword(plainPassword, hashedPassword) {
  try {
    // Vérification sécurisée temps constant
    const isMatch = await bcrypt.compare(plainPassword, hashedPassword);
    return isMatch;
  } catch (error) {
    throw new Error('Erreur vérification: ' + error.message);
  }
}

// Usage pratique
(async () => {
  const password = 'MonMotDePasseSecurise123!';
  
  // Hash
  const hash = await hashPassword(password);
  console.log('Hash:', hash);
  
  // Vérification
  const isValid = await verifyPassword(password, hash);
  console.log('Valide:', isValid); // true
  
  // Mauvais mot de passe
  const isInvalid = await verifyPassword('BadPassword', hash);
  console.log('Invalide:', isInvalid); // false
})();

Python - Optimisé & Sécurisé

import bcrypt
import time

# Configuration sécurisée
SALT_ROUNDS = 12

def hash_password(plain_password: str) -> str:
    """Hash sécurisé d'un mot de passe"""
    # Conversion en bytes
    password_bytes = plain_password.encode('utf-8')
    
    # Génération salt + hash
    salt = bcrypt.gensalt(rounds=SALT_ROUNDS)
    hash_bytes = bcrypt.hashpw(password_bytes, salt)
    
    # Retour en string
    return hash_bytes.decode('utf-8')

def verify_password(plain_password: str, hashed_password: str) -> bool:
    """Vérification sécurisée mot de passe"""
    password_bytes = plain_password.encode('utf-8')
    hash_bytes = hashed_password.encode('utf-8')
    
    # Vérification temps constant
    return bcrypt.checkpw(password_bytes, hash_bytes)

def benchmark_cost_factor():
    """Benchmark pour choisir le cost factor optimal"""
    password = "TestPassword123!"
    
    for rounds in range(10, 16):
        start_time = time.time()
        hash_password_with_rounds(password, rounds)
        duration = time.time() - start_time
        print(f"Rounds {rounds}: {duration:.3f}s")

def hash_password_with_rounds(password: str, rounds: int) -> str:
    password_bytes = password.encode('utf-8')
    salt = bcrypt.gensalt(rounds=rounds)
    return bcrypt.hashpw(password_bytes, salt).decode('utf-8')

# Exemple d'utilisation
if __name__ == "__main__":
    password = "MonMotDePasseSecurise123!"
    
    # Hash
    hashed = hash_password(password)
    print(f"Hash: {hashed}")
    
    # Vérification
    is_valid = verify_password(password, hashed)
    print(f"Valide: {is_valid}")
    
    # Test échec
    is_invalid = verify_password("BadPassword", hashed)
    print(f"Invalide: {is_invalid}")

Intégration Sécurité Avancée

// Exemple d'intégration sécurisée complète

class PasswordManager {
  constructor() {
    this.SALT_ROUNDS = 12;
    this.MAX_PASSWORD_LENGTH = 72; // Limite bcrypt
    this.MIN_PASSWORD_LENGTH = 8;
  }

  validatePassword(password) {
    if (password.length < this.MIN_PASSWORD_LENGTH) {
      throw new Error('Mot de passe trop court');
    }
    if (password.length > this.MAX_PASSWORD_LENGTH) {
      throw new Error('Mot de passe trop long (max 72 chars)');
    }
    // Autres validations...
  }

  async hashPassword(password) {
    this.validatePassword(password);
    
    // Mesure du temps (pour monitoring)
    const start = Date.now();
    const hash = await bcrypt.hash(password, this.SALT_ROUNDS);
    const duration = Date.now() - start;
    
    // Log pour monitoring performance
    console.log(`Password hashed in ${duration}ms`);
    
    return hash;
  }

  async verifyPassword(password, hash) {
    // Protection contre timing attacks
    const start = Date.now();
    
    try {
      const result = await bcrypt.compare(password, hash);
      return result;
    } finally {
      // Temps minimum pour éviter timing attacks
      const elapsed = Date.now() - start;
      if (elapsed < 100) {
        await new Promise(resolve => 
          setTimeout(resolve, 100 - elapsed)
        );
      }
    }
  }

  // Mise à jour du cost factor si nécessaire
  async upgradeHashIfNeeded(password, currentHash) {
    const rounds = this.extractRounds(currentHash);
    
    if (rounds < this.SALT_ROUNDS) {
      console.log('Upgrading hash cost factor');
      return await this.hashPassword(password);
    }
    
    return currentHash;
  }

  extractRounds(hash) {
    const parts = hash.split('$');
    return parseInt(parts[2]);
  }
}

⚡ Points Clés Implémentation

🔧 Configuration
  • • Cost factor 12+ obligatoire production
  • • Limitation longueur password (72 chars max)
  • • Timeout protection contre DoS
  • • Logging et monitoring performance
🛡️ Sécurité
  • • Validation stricte des inputs
  • • Protection timing attacks
  • • Gestion sécurisée des erreurs
  • • Upgrade automatique cost factor

Actions Rapides

Statistiques

Analyses bcrypt892K+
Années service25
Vulnérabilités0
Cost recommandé12
Temps hash (r=12)~250ms

vs Autres Algorithmes

vs Argon2Plus mature
vs scryptPlus simple
vs PBKDF2Plus résistant
Attention

Testez toujours le temps de hash sur votre infrastructure avant de déployer. Un cost factor trop élevé peut créer des DoS involontaires.

Ressources et Implémentations

Paper Original
Provos & Mazières (1999)
node.bcrypt.js
Implémentation Node.js référence
bcrypt Python
PyPI package officiel
PHP password_hash()
Fonction native PHP
OpenBSD bcrypt
Implémentation C originale
OWASP Guide
Bonnes pratiques sécurité

bcrypt : Le Choix Sûr pour 2024 et au-delà

Après 25 ans de service, bcrypt reste incontournable pour le hachage de mots de passe. Son adoption universelle, sa résistance éprouvée, et sa simplicité d'implémentation en font le choix privilégié des experts pour la protection des credentials utilisateurs.

25 ans
Sans compromission
Universel
Support tous langages
Futur-proof
Cost factor évolutif