TRM-coding | c4b4f3d | 2025-06-18 19:02:46 +0800 | [diff] [blame] | 1 | // 密码加密工具函数 |
| 2 | import CryptoJS from 'crypto-js'; |
| 3 | |
| 4 | /** |
| 5 | * 使用 SHA256 加密密码 |
| 6 | * @param {string} password 原始密码 |
| 7 | * @returns {string} 加密后的密码 |
| 8 | */ |
| 9 | export const hashPassword = (password) => { |
| 10 | if (!password || typeof password !== 'string') { |
| 11 | throw new Error('密码必须是非空字符串'); |
| 12 | } |
| 13 | |
| 14 | return CryptoJS.SHA256(password).toString(); |
| 15 | }; |
| 16 | |
| 17 | /** |
| 18 | * 验证密码是否已经被加密 |
| 19 | * @param {string} password 密码字符串 |
| 20 | * @returns {boolean} 是否为已加密的密码(64位十六进制字符串) |
| 21 | */ |
| 22 | export const isEncryptedPassword = (password) => { |
| 23 | if (!password || typeof password !== 'string') { |
| 24 | return false; |
| 25 | } |
| 26 | |
| 27 | // SHA256 加密后是64位十六进制字符串 |
| 28 | return /^[a-f0-9]{64}$/i.test(password); |
| 29 | }; |
| 30 | |
| 31 | /** |
| 32 | * 安全的密码加密函数,避免重复加密 |
| 33 | * @param {string} password 密码 |
| 34 | * @returns {string} 加密后的密码 |
| 35 | */ |
| 36 | export const safeHashPassword = (password) => { |
| 37 | if (!password) { |
| 38 | throw new Error('密码不能为空'); |
| 39 | } |
| 40 | |
| 41 | // 如果已经是加密的密码,直接返回 |
| 42 | if (isEncryptedPassword(password)) { |
| 43 | return password; |
| 44 | } |
| 45 | |
| 46 | // 否则进行加密 |
| 47 | return hashPassword(password); |
| 48 | }; |