js实现密码
密码强度验证
使用正则表达式验证密码强度是一种常见方法。以下代码检查密码是否包含大小写字母、数字和特殊字符,且长度至少为8位:
function checkPasswordStrength(password) {
const strongRegex = /^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#$%^&*])(?=.{8,})/;
return strongRegex.test(password);
}
密码哈希处理
前端密码哈希处理可增加安全性,推荐使用PBKDF2算法:
async function hashPassword(password) {
const encoder = new TextEncoder();
const salt = window.crypto.getRandomValues(new Uint8Array(16));
const keyMaterial = await window.crypto.subtle.importKey(
'raw',
encoder.encode(password),
{name: 'PBKDF2'},
false,
['deriveBits']
);
const key = await window.crypto.subtle.deriveBits(
{
name: 'PBKDF2',
salt,
iterations: 100000,
hash: 'SHA-256'
},
keyMaterial,
256
);
return {salt, key};
}
密码输入框安全
实现密码显示切换功能:
function setupPasswordToggle() {
const passwordInput = document.getElementById('password');
const toggleBtn = document.getElementById('toggle-password');
toggleBtn.addEventListener('click', () => {
const type = passwordInput.getAttribute('type') === 'password' ? 'text' : 'password';
passwordInput.setAttribute('type', type);
toggleBtn.textContent = type === 'password' ? '显示' : '隐藏';
});
}
密码策略检查
实现自定义密码策略验证:
function validatePasswordPolicy(password, options = {}) {
const defaults = {
minLength: 8,
requireUpper: true,
requireLower: true,
requireNumber: true,
requireSpecial: true
};
const config = {...defaults, ...options};
const errors = [];
if (password.length < config.minLength) {
errors.push(`密码长度至少为${config.minLength}位`);
}
if (config.requireUpper && !/[A-Z]/.test(password)) {
errors.push('必须包含大写字母');
}
if (config.requireLower && !/[a-z]/.test(password)) {
errors.push('必须包含小写字母');
}
if (config.requireNumber && !/[0-9]/.test(password)) {
errors.push('必须包含数字');
}
if (config.requireSpecial && !/[!@#$%^&*]/.test(password)) {
errors.push('必须包含特殊字符');
}
return {
isValid: errors.length === 0,
errors
};
}
密码生成器
实现随机密码生成功能:
function generatePassword(length = 12) {
const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*';
const array = new Uint32Array(length);
window.crypto.getRandomValues(array);
return Array.from(array, x => chars[x % chars.length]).join('');
}
这些实现方法涵盖了密码处理的常见需求,包括验证、哈希、显示控制和生成。实际应用中应根据具体安全要求进行调整,重要系统应始终在后端进行最终验证和哈希处理。







