YouChain_WMS_Web/nc_wms_web/src/lib/encrypt.ts

121 lines
3.5 KiB
TypeScript
Raw Normal View History

2025-03-14 17:13:19 +08:00
import CryptoJS from 'crypto-js';
import CryptoSM from 'sm-crypto';
function object2string(data) {
if (typeof data === 'object') {
return JSON.stringify(data);
}
let str = JSON.stringify(data);
if (str.startsWith("'") || str.startsWith('"')) {
str = str.substring(1);
}
if (str.endsWith("'") || str.endsWith('"')) {
str = str.substring(0, str.length - 1);
}
return str;
}
/**
*
*/
function stringToHex(str) {
let hex = '';
for(let i = 0; i < str.length; i++) {
hex += str.charCodeAt(i).toString(16).padStart(2, '0');
}
return hex;
}
/*
* -------------------- AES begin --------------------
*
* 1AES128192256128
* 2AES 128bit 16
* 3js使 UCS-2 UTF-16 1
* 4Key 16
*
* -------------------- AES end --------------------
*/
const AES_KEY = '1024lab__1024lab';
const AES = {
encryptData: function (data) {
// AES 加密 并转为 base64
let utf8Data = CryptoJS.enc.Utf8.parse(object2string(data));
const key = CryptoJS.enc.Utf8.parse(AES_KEY);
const encrypted = CryptoJS.AES.encrypt(utf8Data, key, {
mode: CryptoJS.mode.ECB,
padding: CryptoJS.pad.Pkcs7,
});
return CryptoJS.enc.Base64.stringify(encrypted.ciphertext);
},
decryptData: function (data) {
// 第一步Base64 解码
let words = CryptoJS.enc.Base64.parse(data);
// 第二步AES 解密
const key = CryptoJS.enc.Utf8.parse(AES_KEY);
return CryptoJS.AES.decrypt({ ciphertext: words }, key, {
mode: CryptoJS.mode.ECB,
padding: CryptoJS.pad.Pkcs7,
}).toString(CryptoJS.enc.Utf8);
},
};
/*
* -------------------- SM4 begin --------------------
*
* 1SM4 128bit 16
* 2js使 UCS-2 UTF-16 1
* 3java 1
* 4 Key 16
*
* -------------------- SM4 end --------------------
*/
// 秘钥Key 组成为:字母、数字、特殊符号 一共16个即可
const SM4_KEY = '1024lab__1024lab';
const SM4 = {
encryptData: function (data) {
// 第一步SM4 加密
let encryptData = CryptoSM.sm4.encrypt(object2string(data), stringToHex(SM4_KEY));
// 第二步: Base64 编码
return CryptoJS.enc.Base64.stringify(CryptoJS.enc.Utf8.parse(encryptData));
},
decryptData: function (data) {
// 第一步Base64 解码
let words = CryptoJS.enc.Base64.parse(data);
let decode64Str = CryptoJS.enc.Utf8.stringify(words);
// 第二步SM4 解密
return CryptoSM.sm4.decrypt(decode64Str, stringToHex(SM4_KEY));
},
};
// ----------------------- 对外暴露: 加密、解密 -----------------------
// 默认使用SM4算法
const EncryptObject = SM4;
// const EncryptObject = AES;
/**
*
*/
export const encryptData = function (data) {
return !data ? null : EncryptObject.encryptData(data);
};
/**
*
*/
export const decryptData = function (data) {
return !data ? null : EncryptObject.decryptData(data);
};