|
|
|
import JSEncrypt from 'jsencrypt';
|
|
|
|
// 密钥对生成 http://web.chacuo.net/netrsakeypair
|
|
|
|
import { useGlobSetting } from '@/hooks/setting';
|
|
|
|
|
|
|
|
import {sm2} from 'sm-crypto'
|
|
|
|
const globSetting = useGlobSetting();
|
|
|
|
const publicKey = globSetting.rsaPublicKey;
|
|
|
|
|
|
|
|
// 前端不建议存放私钥 不建议解密数据 因为都是透明的意义不大
|
|
|
|
/** ??? 意义何在 */
|
|
|
|
const privateKey = globSetting.rsaPrivateKey;
|
|
|
|
|
|
|
|
// /**
|
|
|
|
// * RSA加密
|
|
|
|
// * @param txt 需要加密的数据
|
|
|
|
// * @returns
|
|
|
|
// */
|
|
|
|
// export function encrypt(txt: string) {
|
|
|
|
// const instance = new JSEncrypt();
|
|
|
|
// instance.setPublicKey(publicKey);
|
|
|
|
// return instance.encrypt(txt);
|
|
|
|
// }
|
|
|
|
|
|
|
|
// /**
|
|
|
|
// * RSA解密
|
|
|
|
// * @param txt 需要解密的数据
|
|
|
|
// * @returns
|
|
|
|
// */
|
|
|
|
// export function decrypt(txt: string) {
|
|
|
|
// const instance = new JSEncrypt();
|
|
|
|
// instance.setPrivateKey(privateKey);
|
|
|
|
// return instance.decrypt(txt);
|
|
|
|
// }
|
|
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
* SM2公钥加密
|
|
|
|
* @param message 待加密数据
|
|
|
|
* @param publicKey 公钥 (以04开头的十六进制字符串)
|
|
|
|
* @returns 十六进制格式的密文
|
|
|
|
*/
|
|
|
|
export function encrypt(message: string) {
|
|
|
|
try {
|
|
|
|
const cipherData = sm2.doEncrypt(message, publicKey,1);
|
|
|
|
|
|
|
|
return cipherData;
|
|
|
|
} catch (error) {
|
|
|
|
throw new Error('SM2加密失败: ' + error.message);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* SM2私钥解密
|
|
|
|
* @param ciphertext 密文(十六进制格式)
|
|
|
|
* @param privateKey 私钥(十六进制格式)
|
|
|
|
* @returns 解密后的明文
|
|
|
|
*/
|
|
|
|
export function decrypt(ciphertext: string) {
|
|
|
|
try {
|
|
|
|
//去掉密文的开头的04
|
|
|
|
const ciphertextHex = ciphertext.slice(2);
|
|
|
|
const decrypted = sm2.doDecrypt(ciphertextHex, privateKey,1);
|
|
|
|
|
|
|
|
return decrypted;
|
|
|
|
} catch (error) {
|
|
|
|
throw new Error('SM2解密失败: ' + error.message);
|
|
|
|
}
|
|
|
|
}
|