| // 密码加密工具函数 |
| import CryptoJS from 'crypto-js'; |
| |
| /** |
| * 使用 SHA256 加密密码 |
| * @param {string} password 原始密码 |
| * @returns {string} 加密后的密码 |
| */ |
| export const hashPassword = (password) => { |
| if (!password || typeof password !== 'string') { |
| throw new Error('密码必须是非空字符串'); |
| } |
| |
| return CryptoJS.SHA256(password).toString(); |
| }; |
| |
| /** |
| * 验证密码是否已经被加密 |
| * @param {string} password 密码字符串 |
| * @returns {boolean} 是否为已加密的密码(64位十六进制字符串) |
| */ |
| export const isEncryptedPassword = (password) => { |
| if (!password || typeof password !== 'string') { |
| return false; |
| } |
| |
| // SHA256 加密后是64位十六进制字符串 |
| return /^[a-f0-9]{64}$/i.test(password); |
| }; |
| |
| /** |
| * 安全的密码加密函数,避免重复加密 |
| * @param {string} password 密码 |
| * @returns {string} 加密后的密码 |
| */ |
| export const safeHashPassword = (password) => { |
| if (!password) { |
| throw new Error('密码不能为空'); |
| } |
| |
| // 如果已经是加密的密码,直接返回 |
| if (isEncryptedPassword(password)) { |
| return password; |
| } |
| |
| // 否则进行加密 |
| return hashPassword(password); |
| }; |