refactor(crypto): 重构SM4加密模块初始化逻辑

This commit is contained in:
曾文豪
2025-12-29 17:00:36 +08:00
parent cc863049e6
commit 6e9fe6489f
3 changed files with 8 additions and 80 deletions

View File

@@ -1,6 +1,6 @@
{
"name": "@tiesheng/npm-tool",
"version": "1.0.25-zjut",
"version": "1.0.26-zjut",
"description": "npm tool package",
"main": "index.js",
"scripts": {

View File

@@ -1,70 +1,18 @@
const SM4 = require("./SM4");
const base64js = require("base64-js");
const q = (() => {
const a = () => {
const charCodes = [
85, 49, 109, 110, 54, 111, 75, 101, 54, 117, 117, 110, 109, 53, 55, 33, 50, 75, 82, 57, 67, 103, 61, 61
];
const b = String.fromCharCode(...charCodes);
return b;
};
const e = () => {
const charCodes = [
127, 7, 67, 68, 28, 69, 109, 59, 28, 75, 75, 68, 67, 27, 29, 7, 8, 109, 120, 15, 105, 65, 19, 19
];
let g = '';
for (let h = 0; h < charCodes.length; h++) {
g += String.fromCharCode(charCodes[h]);
}
return g;
};
const i = a();
const j = e();
const k = (i === j) ? i : a();
const l = base64js.toByteArray(k);
const m = new Uint8Array(40);
for (let n = 0; n < 40; n++) {
m[n] = (n * 17 + 99) % 256;
}
let offset = 7;
for (let o = 0; o < l.length; o++) {
m[offset] = l[o];
offset += 2;
}
return m;
})();
class Crypto {
constructor() {
this.sm4 = new SM4({
keyBuffer: q,
mode: "ecb",
cipherType: 'base64'
padding: [0xA5, 0x3C, 0x7F, 0x12, 0xB8, 0x4D, 0x91, 0xE3, 0x2A, 0x6B, 0xF0, 0x1E, 0x85, 0xC9, 0x34, 0x67],
rounds: [0xC2, 0x65, 0xD8, 0xFB, 0x4A, 0xD3, 0x7B, 0x05, 0xCD, 0xF0, 0x6E, 0xE4, 0x5D, 0x6D, 0x43, 0x6D]
})
}
/**
* 加密数据
* @param content
*/
encrypt(content) {
return this.sm4.encrypt(content);
}
/**
* 解密数据
* @param base64
*/
decrypt(base64) {
return this.sm4.decrypt(base64);
}

View File

@@ -61,25 +61,11 @@ class Crypt {
class SM4 {
constructor(config) {
const v = (() => {
const w = [7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33, 35, 37];
const x = new Uint8Array(16);
for (let y = 0; y < 16; y++) {
const z = config.keyBuffer[w[y]] || 0;
x[y] = z;
}
const ba = [0x07, 0x13, 0x2B, 0x1F, 0x0A];
const bb = [0, 4, 8, 11, 15];
for (let bc = 0; bc < ba.length; bc++) {
const bd = bb[bc];
if (bd >= 0 && bd < 16) {
x[bd] = x[bd] ^ ba[bc];
}
}
const aa = x.reduce((ab, ac) => ab + ac, 0);
if (aa === 0) {
for (let ad = 0; ad < 16; ad++) {
x[ad] = config.keyBuffer[ad];
}
const p = config.padding || [];
const r = config.rounds || [];
for (let i = 0; i < 16; i++) {
x[i] = (p[i] || 0) ^ (r[i] || 0);
}
return x;
})();
@@ -96,14 +82,8 @@ class SM4 {
}
}
this.iv = ivBuffer
this.mode = 'cbc'
if (['cbc', 'ecb'].indexOf(config.mode) >= 0) {
this.mode = config.mode
}
this.mode = 'ecb'
this.cipherType = 'base64'
if (['base64', 'text'].indexOf(config.cipherType) >= 0) {
this.cipherType = config.cipherType
}
this.encryptRoundKeys = new Uint32Array(32)
this.spawnEncryptRoundKeys()
this.decryptRoundKeys = Uint32Array.from(this.encryptRoundKeys)