Files
gofly-platform-services/zlt-web/react-web-next/src/utils/rsaUtil.ts
T

207 lines
6.0 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import * as JSEncryptLib from 'jsencrypt';
// 确定正确的JSEncrypt构造函数
const JSEncrypt = JSEncryptLib.JSEncrypt || JSEncryptLib.default || JSEncryptLib;
/**
* RSA加密工具类 - 与后端RSAUtil对应
* 用于前端敏感数据加密,后端解密
*/
export class RSAUtil {
// 与后端genKeyPair()方法中固定的公钥保持一致
private static readonly PUBLIC_KEY_RAW =
'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCGu7lYGfEtMICO8kREJrObu0Hy' +
'pF7R9iEIefyxApmB6wJ/y3Rg/eBO6kLDCo18hYZ3ZNxKp5CMymZvXDh5j+sd7IHm' +
'tUh6sEZzpXExQJIzT8gA1SULd+iXe4V9zt2AcbROIi94vA6lOfmtON28Ex+uAlLK' +
'N/iJDXFFXdEOmfdqhwIDAQAB';
// 格式化为PEM格式的公钥
private static readonly PUBLIC_KEY =
'-----BEGIN PUBLIC KEY-----\n' +
RSAUtil.PUBLIC_KEY_RAW +
'\n-----END PUBLIC KEY-----';
// 由于 jsencrypt 未提供完善的类型定义,这里使用 any 规避类型问题
private static jsEncrypt: any = null;
/**
* 获取或创建JSEncrypt实例
*/
private static getJSEncryptInstance(): any {
try {
// 每次都创建新实例,避免缓存问题
const jsEncrypt: any = new JSEncrypt();
console.log('创建新的JSEncrypt实例');
// 首先尝试PEM格式
jsEncrypt.setPublicKey(this.PUBLIC_KEY);
if (!jsEncrypt.getPublicKey()) {
console.log('PEM格式失败,尝试原始格式');
jsEncrypt.setPublicKey(this.PUBLIC_KEY_RAW);
}
// 最终验证
if (!jsEncrypt.getPublicKey()) {
throw new Error('公钥设置失败');
}
// 验证encrypt方法是否存在
if (typeof jsEncrypt.encrypt !== 'function') {
throw new Error('JSEncrypt实例的encrypt方法不存在');
}
console.log('JSEncrypt实例创建成功,encrypt方法类型:', typeof jsEncrypt.encrypt);
return jsEncrypt;
} catch (error) {
console.error('JSEncrypt实例创建失败:', error);
throw error;
}
}
/**
* 使用公钥加密数据
* @param data 要加密的明文数据
* @returns 加密后的Base64字符串,已进行URL编码处理(将"/"替换为"%2F")
*/
public static encrypt(data: string): string | null {
try {
console.log('开始创建JSEncrypt实例...');
const jsEncryptInstance = this.getJSEncryptInstance();
console.log('开始执行加密操作...');
const encrypted = jsEncryptInstance.encrypt(data);
if (!encrypted) {
console.error('RSA加密失败,encrypt方法返回null或false');
return null;
}
console.log('加密成功,原始结果长度:', encrypted.length);
// 与后端encryptOne方法保持一致,将"/"替换为"%2F"
const result = encrypted.replace(/\//g, '%2F');
console.log('URL编码后长度:', result.length);
return result;
} catch (error) {
console.error('RSA加密异常:', error);
return null;
}
}
/**
* 直接加密方法 - 绕过类方法调用
*/
public static directEncrypt(data: string): string | null {
try {
console.log('直接加密方法,数据长度:', data.length);
console.log('JSEncrypt类型:', typeof JSEncrypt);
if (typeof JSEncrypt !== 'function') {
console.error('JSEncrypt不是函数');
return null;
}
const crypt = new JSEncrypt();
console.log('JSEncrypt实例创建成功,实例类型:', typeof crypt);
console.log('encrypt方法类型:', typeof crypt.encrypt);
// 设置公钥
crypt.setPublicKey(this.PUBLIC_KEY_RAW);
console.log('公钥设置完成');
// 执行加密
const encrypted = crypt.encrypt(data);
console.log('加密结果:', encrypted ? '成功' : '失败');
if (encrypted) {
return encrypted.replace(/\//g, '%2F');
}
return null;
} catch (error) {
console.error('直接加密异常:', error);
return null;
}
}
/**
* 加密密码 - 专门用于密码字段的加密
* @param password 原始密码
* @returns 加密后的密码字符串
*/
public static encryptPassword(password: string): string | null {
if (!password || password.trim() === '') {
return null;
}
try {
if (typeof JSEncrypt !== 'function') {
return null;
}
const crypt = new JSEncrypt();
crypt.setPublicKey(RSAUtil.PUBLIC_KEY_RAW);
const encrypted = crypt.encrypt(password);
if (encrypted) {
return encrypted.replace(/\//g, '%2F');
}
return null;
} catch (error) {
console.error('RSA加密失败:', error);
return null;
}
}
/**
* 批量加密对象中的敏感字段
* @param data 包含敏感字段的对象
* @param sensitiveFields 需要加密的字段名数组
* @returns 处理后的对象(敏感字段已加密)
*/
public static encryptSensitiveFields<T extends Record<string, any>>(
data: T,
sensitiveFields: (keyof T)[]
): T {
const result = { ...data };
sensitiveFields.forEach(field => {
if (result[field] && typeof result[field] === 'string') {
const encrypted = this.encrypt(result[field] as string);
if (encrypted) {
result[field] = encrypted as T[keyof T];
}
}
});
return result;
}
/**
* 检查是否已加密(简单判断是否包含Base64字符和%2F)
* @param data 要检查的数据
* @returns 是否已加密
*/
public static isEncrypted(data: string): boolean {
if (!data) return false;
// 简单判断:包含%2F且长度较长且符合Base64模式
return data.includes('%2F') && data.length > 100 && /^[A-Za-z0-9+%=\/]+$/.test(data);
}
/**
* 获取公钥(仅用于调试,生产环境不建议暴露)
* @returns 公钥字符串
*/
public static getPublicKey(): string {
return this.PUBLIC_KEY;
}
}
// 默认导出
export default RSAUtil;
// 便捷方法导出
export const encryptPassword = RSAUtil.encryptPassword;
export const encryptData = RSAUtil.encrypt;
export const encryptSensitiveFields = RSAUtil.encryptSensitiveFields;