77 lines
2.2 KiB
TypeScript
77 lines
2.2 KiB
TypeScript
import * as JSEncryptLib from 'jsencrypt';
|
|
|
|
// 确定正确的JSEncrypt构造函数
|
|
const JSEncrypt = JSEncryptLib.JSEncrypt || JSEncryptLib.default || JSEncryptLib;
|
|
|
|
/**
|
|
* RSA加密工具类 - 与后端RSAUtil对应
|
|
*/
|
|
export class RSAUtil {
|
|
private static readonly PUBLIC_KEY_RAW =
|
|
'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCGu7lYGfEtMICO8kREJrObu0Hy' +
|
|
'pF7R9iEIefyxApmB6wJ/y3Rg/eBO6kLDCo18hYZ3ZNxKp5CMymZvXDh5j+sd7IHm' +
|
|
'tUh6sEZzpXExQJIzT8gA1SULd+iXe4V9zt2AcbROIi94vA6lOfmtON28Ex+uAlLK' +
|
|
'N/iJDXFFXdEOmfdqhwIDAQAB';
|
|
|
|
private static readonly PUBLIC_KEY =
|
|
'-----BEGIN PUBLIC KEY-----\n' +
|
|
RSAUtil.PUBLIC_KEY_RAW +
|
|
'\n-----END PUBLIC KEY-----';
|
|
|
|
private static getJSEncryptInstance(): any {
|
|
try {
|
|
const jsEncrypt: any = new JSEncrypt();
|
|
jsEncrypt.setPublicKey(this.PUBLIC_KEY);
|
|
if (!jsEncrypt.getPublicKey()) {
|
|
jsEncrypt.setPublicKey(this.PUBLIC_KEY_RAW);
|
|
}
|
|
if (!jsEncrypt.getPublicKey()) {
|
|
throw new Error('公钥设置失败');
|
|
}
|
|
return jsEncrypt;
|
|
} catch (error) {
|
|
console.error('JSEncrypt实例创建失败:', error);
|
|
throw error;
|
|
}
|
|
}
|
|
|
|
public static encrypt(data: string): string | null {
|
|
try {
|
|
const jsEncryptInstance = this.getJSEncryptInstance();
|
|
const encrypted = jsEncryptInstance.encrypt(data);
|
|
if (!encrypted) {
|
|
return null;
|
|
}
|
|
return encrypted.replace(/\//g, '%2F');
|
|
} catch (error) {
|
|
console.error('RSA加密异常:', error);
|
|
return null;
|
|
}
|
|
}
|
|
|
|
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;
|
|
}
|
|
}
|
|
}
|
|
|
|
export default RSAUtil;
|
|
export const encryptPassword = RSAUtil.encryptPassword;
|
|
export const encryptData = RSAUtil.encrypt;
|