Passwords are the most fundamental and important security defense in the digital world. Despite the emergence of new technologies like biometrics and multi-factor authentication, passwords remain a core component of identity verification. This article starts from the basic principles of password security,深入探讨密码强度计算、常见攻击方式、密码生成原理、密码管理器工作机制,以及经过行业验证的最佳实践,帮助你构建更安全的密码体系。
I. Overview of Password Security
Password security is the cornerstone of information security. According to the Verizon 2025 Data Breach Investigations Report, approximately 82% of data breaches involve human factors, with weak passwords and stolen credentials being the most common intrusion vectors. Understanding the importance and basic principles of password security is the first step in protecting personal and organizational information security.
Core Principles of Password Security
- Uniqueness: Use a unique password for each account. Password reuse is the biggest security risk.
- Length First: Password length improves security more than complexity.
- Randomness: Predictable patterns (birthdays, names) significantly reduce password strength.
- Regular Updates: Important account passwords should be changed regularly, especially when compromise is suspected.
- Multi-Factor Authentication: Passwords should not be the only authentication method.
💡 Tip:Using a password manager is the best way to achieve password uniqueness. You only need to remember one master password, and all other passwords are generated and securely stored by the manager.
II. Password Strength and Entropy Calculation
Password strength is typically measured by "entropy", in bits. Password entropy represents the degree of uncertainty of a password — the higher the entropy, the harder the password is to crack. The entropy calculation formula is based on the password's character set size and password length.
Entropy Calculation Formula
The formula for calculating password entropy is: H = L × log₂(N), where H is entropy (in bits), L is password length, and N is the character set size (number of possible characters).
| Character Type | Character Count | Example | Entropy per Character |
|---|---|---|---|
| Digits only | 10 | 0-9 | ~3.32 bits |
| Lowercase letters | 26 | a-z | ~4.70 bits |
| Upper + lowercase letters | 52 | a-z, A-Z | ~5.70 bits |
| Alphanumeric | 62 | a-z, A-Z, 0-9 | ~5.95 bits |
| All printable characters | 94 | 字母、数字、符号 | ~6.55 bits |
| Diceware word list | 7776 | 英文常用词 | ~12.92 bits/词 |
Password Strength Level Reference
| Entropy Range | Strength Level | Use Case | Brute Force Time (assuming 1 billion attempts/sec) |
|---|---|---|---|
| < 40 bits | Very Weak | Not recommended for any scenario | Instant ~ minutes |
| 40-60 bits | Medium | Non-critical accounts, temporary use | Minutes ~ years |
| 60-80 bits | Strong | Regular website accounts | Years ~ thousands of years |
| 80-120 bits | Very Strong | Important accounts, financial accounts | Thousands of years ~ incalculable |
| > 120 bits | Extremely Strong | Password manager master password, encryption keys | Theoretically uncrackable |
Entropy Calculation Example
// 密码熵值计算函数
function calculateEntropy(password) {
let charsetSize = 0;
// 检查是否包含数字
if (/[0-9]/.test(password)) charsetSize += 10;
// 检查是否包含小写字母
if (/[a-z]/.test(password)) charsetSize += 26;
// 检查是否包含大写字母
if (/[A-Z]/.test(password)) charsetSize += 26;
// 检查是否包含特殊符号
if (/[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]/.test(password)) charsetSize += 32;
// 计算熵值: H = L * log2(N)
const entropy = password.length * Math.log2(charsetSize);
return {
entropy: Math.round(entropy * 100) / 100,
charsetSize: charsetSize,
length: password.length
};
}
// 示例计算
console.log(calculateEntropy('123456'));
// { entropy: 19.93, charsetSize: 10, length: 6 }
console.log(calculateEntropy('password'));
// { entropy: 37.6, charsetSize: 26, length: 8 }
console.log(calculateEntropy('P@ssw0rd'));
// { entropy: 52.44, charsetSize: 94, length: 8 }
console.log(calculateEntropy('Tr0ub4dor&3'));
// { entropy: 72.09, charsetSize: 94, length: 11 }
console.log(calculateEntropy('correct horse battery staple'));
// Diceware 风格密码 (4个常用词): 约 51 bits
III. Common Password Attack Methods
Understanding how attackers crack passwords helps us better protect ourselves. Here are four of the most common password attack methods.
3.1 Dictionary Attack
A dictionary attack is one of the most common password cracking methods. Attackers use a pre-prepared list of passwords (dictionary) and try them one by one to log in. These dictionaries typically contain common passwords, leaked passwords, common words, names, dates, etc.
- Principle: Exploits the weakness that users tend to use memorable passwords
- Common Dictionaries: RockYou, Have I Been Pwned leaked databases, common word lists
- Defense: Use randomly generated passwords, avoid common words and patterns
3.2 Brute Force Attack
A brute force attack tries all possible character combinations until the correct password is found. Theoretically, brute force can crack any password, but as password length and complexity increase, the time required grows exponentially.
- Principle: Exhaustive search of all possible character combinations
- Speed: Modern GPUs can attempt billions of hash calculations per second
- Defense: Increase password length (entropy), use slow hash algorithms (bcrypt, Argon2)
3.3 Rainbow Table Attack
A rainbow table is a precomputed table of hash values used to quickly look up the hash value corresponding to a password. If an attacker obtains password hashes (e.g., through a database leak), they can use a rainbow table to quickly reverse-engineer the original passwords.
- Principle: Trading space for time, precomputing hash chains
- Prerequisite: Attacker has already obtained password hashes
- Defense: Use salt — each password uses a unique random salt
3.4 Social Engineering
Social engineering does not involve technical cracking but obtains passwords through psychological manipulation, deception, and other means. This is the most difficult attack method to defend against because it targets human weaknesses rather than technical vulnerabilities.
- Phishing: Forging login pages to trick users into entering passwords
- Pretexting: Posing as a trusted person to obtain information
- Shoulder Surfing: Peeking while users enter passwords
- Defense: Improve security awareness, verify requester identity, enable multi-factor authentication
| Attack Method | Technical Difficulty | Success Rate | Primary Defense |
|---|---|---|---|
| Dictionary Attack | Low | High (against weak passwords) | Strong passwords, password policies |
| Brute Force | Medium | Low (against strong passwords) | Long passwords, slow hashing |
| Rainbow Table | Medium | Medium (without salt) | Salted hashing |
| Social Engineering | Low | High | Security awareness, MFA |
IV. Password Generation Principles
Secure password generation relies on high-quality random numbers. Understanding the principles of random number generation helps us judge whether a password generator is secure and reliable.
4.1 Pseudo-Random Number Generator (PRNG)
A Pseudo-Random Number Generator (PRNG) uses a deterministic algorithm to generate a sequence of numbers that appear random. It requires a "seed" as the initial value, and the same seed will produce the same random sequence.
- Characteristics: Deterministic, reproducible, fast
- Common Algorithms: Mersenne Twister (MT19937), Linear Congruential Generator (LCG)
- Security: Not suitable for cryptographic purposes; seed leakage makes it completely predictable
- Use Cases: Games, simulations, testing, and other non-security scenarios
4.2 Cryptographically Secure Pseudo-Random Number Generator (CSPRNG)
A Cryptographically Secure Pseudo-Random Number Generator (CSPRNG) is a random number generator specifically designed for cryptographic applications. It not only passes statistical randomness tests but also resists various cryptographic attacks.
- Characteristics: Unpredictability, forward secrecy, diverse entropy sources
- Entropy Sources: Keyboard input timing, mouse movement, disk I/O latency, network packet timing, etc.
- Common Implementations: /dev/urandom (Linux), CryptGenRandom (Windows), SecRandomCopyBytes (macOS)
- Web Standard: Web Crypto API's crypto.getRandomValues()
Secure Password Generation with Web Crypto API
// 使用 Web Crypto API 生成安全随机密码
function generateSecurePassword(length = 16, options = {}) {
const {
includeUppercase = true,
includeLowercase = true,
includeNumbers = true,
includeSymbols = true
} = options;
// 构建字符集
let charset = '';
if (includeLowercase) charset += 'abcdefghijklmnopqrstuvwxyz';
if (includeUppercase) charset += 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
if (includeNumbers) charset += '0123456789';
if (includeSymbols) charset += '!@#$%^&*()_+-=[]{}|;:,.<>?';
if (charset.length === 0) {
throw new Error('At least one character type must be selected');
}
// 使用密码学安全的随机数生成器
const array = new Uint32Array(length);
window.crypto.getRandomValues(array);
// 生成密码(使用模运算减少偏置)
let password = '';
const charsetLength = charset.length;
// 使用拒绝采样避免模运算偏置
const maxValid = Math.floor(0xFFFFFFFF / charsetLength) * charsetLength;
for (let i = 0; i < length; i++) {
let randomValue = array[i];
// 拒绝采样:如果随机值超过最大有效值,重新生成
while (randomValue >= maxValid) {
const newArray = new Uint32Array(1);
window.crypto.getRandomValues(newArray);
randomValue = newArray[0];
}
password += charset[randomValue % charsetLength];
}
return password;
}
// 生成不同类型的密码
console.log(generateSecurePassword(16));
// 包含所有字符类型的 16 位密码
console.log(generateSecurePassword(20, { includeSymbols: false }));
// 仅字母数字的 20 位密码
console.log(generateSecurePassword(32, {
includeUppercase: true,
includeLowercase: true,
includeNumbers: true,
includeSymbols: true
}));
// 32 位高强度密码
⚠️ Important:Never use Math.random() to generate passwords. Math.random() is a pseudo-random number generator and is not cryptographically secure — its output is predictable. Always use crypto.getRandomValues() or an equivalent CSPRNG.
V. How Password Managers Work
A password manager is a tool that helps users generate, store, and manage passwords. It typically uses a single master password to protect all stored passwords, employing strong encryption algorithms to ensure data security.
How It Works
- Master Password Derivation: Uses a key derivation function (such as PBKDF2, Argon2) to generate an encryption key from the master password
- Data Encryption: Encrypts the password database using symmetric encryption algorithms like AES-256
- Secure Storage: The encrypted database is stored locally or in the cloud
- Auto-Fill: Automatically fills passwords through browser extensions or apps
- Sync Mechanism: Synchronizes the encrypted database across multiple devices
Key Derivation Functions (KDF)
The role of a key derivation function is to convert a user's master password into an encryption key, while deliberately slowing down computation speed to resist brute force attacks. Here are three common KDFs:
| Algorithm | Design Goal | Memory Requirement | GPU Resistance |
|---|---|---|---|
| PBKDF2 | Standard compliance, wide compatibility | Low | Weak |
| bcrypt | Adaptive cost, battle-tested | Medium | Medium |
| Argon2 | Memory hardness, modern design | High | Strong |
Zero-Knowledge Architecture
Many password managers adopt a "zero-knowledge" architecture, meaning the service provider cannot access users' password data. Encryption and decryption both happen locally on the user's device, and the server only stores encrypted binary data.
- End-to-End Encryption: Data is encrypted before leaving the device
- Server-Side Ignorance: The service provider cannot read user data
- Master Password Never Transmitted: The master password is never sent to the server
- Risk: Forgetting the master password means data cannot be recovered
VI. Password Best Practices
6.1 Password Creation Best Practices
- Use a password generator to create random passwords; don't try to invent them yourself
- Passwords should be at least 12 characters long; 16+ characters recommended for important accounts
- Mix uppercase and lowercase letters, numbers, and special symbols
- Avoid using personal information (names, birthdays, phone numbers, etc.)
- Avoid common password patterns (e.g., password123, qwerty)
- Use a unique password for each account; never reuse passwords
6.2 Password Management Best Practices
- Use a trusted password manager (e.g., 1Password, Bitwarden, KeePass)
- Set a strong master password for your password manager and enable multi-factor authentication
- Regularly check if passwords have been leaked (using services like Have I Been Pwned)
- Regularly change passwords for high-risk accounts (e.g., email, online banking)
- Don't save passwords in your browser (unless using a password manager extension)
- Don't record passwords in plaintext (paper notes, electronic documents, etc.)
6.3 Password Usage Best Practices
- Always log out of accounts after using public devices
- Be wary of phishing sites; always verify that the URL is correct
- Don't send passwords via email or instant messaging tools
- Use auto-fill to avoid shoulder surfing
- Change passwords immediately and check account activity if you suspect a leak
- Enable multi-factor authentication for important accounts
VII. Multi-Factor Authentication
Multi-Factor Authentication (MFA) requires users to provide two or more different types of authentication factors, greatly improving account security. Even if a password is leaked, attackers cannot log in to the account.
Authentication Factor Types
- Knowledge Factor: Something you know (password, PIN, security questions)
- Possession Factor: Something you have (phone, hardware key, smart card)
- Inherence Factor: Something you are (fingerprint, facial recognition, iris scan)
- Location Factor: Where you are (GPS location, IP address)
Comparison of Common MFA Methods
// TOTP (基于时间的一次性密码) 生成示例
function generateTOTP(secret, timeStep = 30) {
// 获取当前时间戳(秒)
const epoch = Math.floor(Date.now() / 1000);
// 计算时间计数器
const counter = Math.floor(epoch / timeStep);
// 将计数器转换为字节
const counterBytes = new Uint8Array(8);
for (let i = 7; i >= 0; i--) {
counterBytes[i] = counter & 0xff;
counter = counter >>> 8;
}
// 使用 HMAC-SHA1 计算哈希
// 注意:实际实现需要使用 HMAC 算法
// 这里仅展示概念
console.log('TOTP counter:', Math.floor(Date.now() / 1000 / timeStep));
// 生成 6 位数字验证码
// ...
}
// 常用 MFA 方式安全性排序(从低到高):
// 1. 短信验证码 (SMS) - 易被 SIM 交换攻击
// 2. 邮件验证码 - 依赖邮箱安全性
// 3. TOTP (Google Authenticator, Authy) - 较安全
// 4. 推送通知 (Microsoft Authenticator) - 较安全
// 5. 硬件密钥 (YubiKey, Titan Security Key) - 最安全
🔐 Recommendation:Prefer hardware security keys (like YubiKey) or TOTP apps (like Google Authenticator, Authy). Avoid SMS verification codes, as SIM swap attacks can easily bypass SMS authentication.
VIII. History of Password Security
The history of password security reflects the ongoing game between attackers and defenders. Understanding this history helps us understand the origins of current security practices.
Development Timeline
- 1960s: Passwords first used in computer systems (CTSS operating system), stored in plaintext
- 1970s: Unix systems introduced the crypt() function, using DES to encrypt stored passwords
- 1990s: Rainbow table concept proposed, MD5 and SHA-1 widely used
- 2000s: GPU-accelerated cracking became widespread, adaptive hash algorithms like bcrypt emerged
- 2010s: Large-scale password leaks became frequent, two-factor authentication became popular
- 2020s: Passwordless authentication on the rise, Passkey and WebAuthn become new standards
Famous Password Leak Incidents
- RockYou (2009): 32 million accounts leaked, passwords stored in plaintext, became the most commonly used password dictionary
- LinkedIn (2012): 165 million password hashes leaked, using weak hashing (SHA-1 without salt)
- eBay (2014): 145 million user data leaked, including encrypted passwords
- Ashley Madison (2015): 37 million user data leaked, caused social concern
- Yahoo (2013-2014): 3 billion accounts leaked, the largest in history
- Facebook (2019): 533 million user data sold on the dark web
IX. Future Trends: The Passwordless Era
Although passwords will still exist for the foreseeable future, passwordless authentication is becoming a new trend. FIDO2/WebAuthn standards and Passkey technology are driving changes in identity authentication.
- Passkey: Based on public key cryptography, uses device biometric authentication
- WebAuthn: W3C standard, supports hardware keys and platform authenticators
- SSO (Single Sign-On): Log in once, access multiple services
- Biometrics: Fingerprint, facial, iris, and other biometric authentication
🛠️ Tool Recommendation:Need to generate secure random passwords? Try ourPassword Generator Tool, which uses the browser's Web Crypto API to generate cryptographically secure random passwords, supporting customizable length, character types, and many other options.
X. Summary
Password security is the first line of defense for digital security. Through this article, we have learned about password entropy calculation methods, common password attack methods, the principles of secure password generation, how password managers work, and industry-validated best practices.
Remember a few key points: Use a password manager to generate unique strong passwords for each account, enable multi-factor authentication for important accounts, be vigilant against social engineering attacks, and regularly check if passwords have been leaked. In today's world where passwords are still widely used, good password habits can effectively protect your digital assets.
As technology develops, passwordless authentication is gradually becoming more widespread, but for the foreseeable future, passwords will remain an important part of identity authentication. Mastering password security knowledge is both a necessity for self-protection and the responsibility of every digital citizen.