import { JSEncrypt } from 'jsencrypt' import { getPublicKey } from '@/api/user' export async function getPasswordPublicKey(): Promise { const res = await getPublicKey() return res.data } export function encryptPassword(plainText: string, publicKey: string): string { const encryptor = new JSEncrypt() encryptor.setPublicKey(formatPublicKey(publicKey)) const encrypted = encryptor.encrypt(plainText) if (!encrypted) { throw new Error('密码加密失败,请刷新页面后重试') } return encrypted } export async function encryptPasswordPayload>( payload: T, fields: Array, ): Promise { const publicKey = await getPasswordPublicKey() const nextPayload = { ...payload } for (const field of fields) { nextPayload[field] = encryptPassword(String(payload[field] || ''), publicKey) as T[keyof T] } return nextPayload } function formatPublicKey(publicKey: string): string { if (!publicKey) { return '' } if (publicKey.includes('BEGIN PUBLIC KEY')) { return publicKey } const normalized = publicKey.replace(/\s+/g, '') const lines = normalized.match(/.{1,64}/g) || [] return ['-----BEGIN PUBLIC KEY-----', ...lines, '-----END PUBLIC KEY-----'].join('\n') }