bcrypt
Créé en 1999 par Provos & Mazières•Blowfish-based
🔑 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
Format de Sortie
Analyse Cost Factor (Recommandations 2024)
| Rounds | Temps | Usage Recommandé | Sécurité |
|---|---|---|---|
| 4 | ~1ms | Tests unitaires uniquement | Faible |
| 8 | ~16ms | Développement local | Insuffisant |
| 10 | ~64ms | Applications legacy | Minimum |
| 12 | ~256ms | Production recommandée 2024 | Excellent |
| 14 | ~1s | Haute sécurité | Maximum |
| 16 | ~4s | Ultra sécurisé (coûteux) | Extreme |
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
CritiqueCost factor adaptatif ralentit exponentiellement les attaques
Salting Automatique
EssentielSel unique intégré, élimine les rainbow tables
Temps Constant
ImportantProtection contre les timing attacks
Évolutivité
Futur-proofAjustement du coût selon la puissance hardware
Protection Multi-Niveaux
- • Rainbow tables : Impossible (sel unique)
- • Force brute : Ralentie exponentiellement
- • Timing attacks : Temps constant
- • GPU/ASIC : Cost factor adaptatif
- • É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
Systèmes Backend
Infrastructure
Implémentations Production
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
- • Cost factor 12+ obligatoire production
- • Limitation longueur password (72 chars max)
- • Timeout protection contre DoS
- • Logging et monitoring performance
- • Validation stricte des inputs
- • Protection timing attacks
- • Gestion sécurisée des erreurs
- • Upgrade automatique cost factor
Statistiques
vs Autres Algorithmes
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
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.