找物源码导读Cocos Creator 3.8 · assets/scripts
0%
已读 0 / 424
目录— 个文件
目录加载中…
…/core/utility/UtilityEncrypt.ts
1/**
2 * 轻量可逆加密工具。
3 * 设计目标:同步、跨平台、低依赖,只用于本地存储/配置混淆,不用于强安全场景。
4 */
5
6interface IEncryptInfo {
7 key: string;
8 iv: string;
9}
10
11export class UtilityEncrypt {
12 private static createMd5(message: string): string {
13 let h1 = 1779033703;
14 let h2 = 3144134277;
15 let h3 = 1013904242;
16 let h4 = 2773480762;
17
18 for (let index = 0; index < message.length; index++) {
19 const charCode = message.charCodeAt(index);
20 h1 = h2 ^ Math.imul(h1 ^ charCode, 597399067);
21 h2 = h3 ^ Math.imul(h2 ^ charCode, 2869860233);
22 h3 = h4 ^ Math.imul(h3 ^ charCode, 951274213);
23 h4 = h1 ^ Math.imul(h4 ^ charCode, 2716044179);
24 }
25
26 h1 = Math.imul(h3 ^ (h1 >>> 18), 597399067);
27 h2 = Math.imul(h4 ^ (h2 >>> 22), 2869860233);
28 h3 = Math.imul(h1 ^ (h3 >>> 17), 951274213);
29 h4 = Math.imul(h2 ^ (h4 >>> 19), 2716044179);
30
31 const toHex = (value: number): string => {
32 return (value >>> 0).toString(16).padStart(8, "0");
33 };
34
35 return `${toHex(h1 ^ h2 ^ h3 ^ h4)}${toHex(h2 ^ h1)}${toHex(h3 ^ h1)}${toHex(h4 ^ h1)}`;
36 }
37
38 public static md5(msg: string): string {
39 return this.createMd5(msg ?? "");
40 }
41
42 /**
43 * 同步轻量加密,输出沿用 {"ct": "..."} 结构,兼容旧存储格式。
44 */
45 public static encrypt(msg: string, info?: IEncryptInfo): string {
46 const sourceBytes = this.stringToBytes(msg ?? '');
47 const encryptedBytes = this.xorBytes(sourceBytes, info);
48 return JSON.stringify({ ct: this.bytesToBase64(encryptedBytes) });
49 }
50
51 /**
52 * 同步轻量解密,兼容 {"ct": "..."} 与纯 base64 两种输入。
53 */
54 public static decrypt(encryptedText: string, info?: IEncryptInfo): string {
55 const cipherText = this.unpackCipherText(encryptedText);
56 const encryptedBytes = this.base64ToBytes(cipherText);
57 const sourceBytes = this.xorBytes(encryptedBytes, info);
58 return this.bytesToString(sourceBytes);
59 }
60
61 /**
62 * 兼容旧异步接口,内部已改为同步处理。
63 */
64 public static aesEncrypt(msg: string, info?: IEncryptInfo): string {
65 try {
66 return this.encrypt(msg, info);
67 } catch (error) {
68 console.error('[UtilityEncrypt] aesEncrypt failed', error);
69 throw error;
70 }
71 }
72
73 /**
74 * 兼容旧异步接口,内部已改为同步处理。
75 */
76 public static aesDecrypt(encryptedJson: string, info?: IEncryptInfo): string {
77 try {
78 return this.decrypt(encryptedJson, info);
79 } catch (error) {
80 console.error('[UtilityEncrypt] aesDecrypt failed', error);
81 throw error;
82 }
83 }
84
85 private static xorBytes(sourceBytes: Uint8Array, info?: IEncryptInfo): Uint8Array {
86 const seedBytes = this.getSeedBytes(info);
87 const result = new Uint8Array(sourceBytes.length);
88
89 for (let index = 0; index < sourceBytes.length; index++) {
90 const seedByte = seedBytes[index % seedBytes.length];
91 const mixByte = (index * 31 + seedBytes[(index + 7) % seedBytes.length]) & 0xff;
92 result[index] = sourceBytes[index] ^ seedByte ^ mixByte;
93 }
94
95 return result;
96 }
97
98 private static getSeedBytes(info?: IEncryptInfo): Uint8Array {
99 const resolvedInfo = {
100 key: info?.key,
101 iv: info?.iv,
102 };
103 const seed = this.md5(`${resolvedInfo.key}|${resolvedInfo.iv}`);
104 return this.stringToBytes(seed);
105 }
106
107 private static unpackCipherText(encryptedText: string): string {
108 try {
109 const json = JSON.parse(encryptedText) as { ct?: string };
110 if (typeof json.ct === 'string') {
111 return json.ct;
112 }
113 } catch (error) {
114 void error;
115 }
116
117 return encryptedText;
118 }
119
120 private static stringToBytes(text: string): Uint8Array {
121 const encodedText = encodeURIComponent(text);
122 const bytes: number[] = [];
123
124 for (let index = 0; index < encodedText.length; index++) {
125 const char = encodedText[index];
126 if ('%' === char) {
127 bytes.push(parseInt(encodedText.slice(index + 1, index + 3), 16));
128 index += 2;
129 continue;
130 }
131 bytes.push(encodedText.charCodeAt(index));
132 }
133
134 return new Uint8Array(bytes);
135 }
136
137 private static bytesToString(bytes: Uint8Array): string {
138 let encodedText = '';
139
140 for (let index = 0; index < bytes.length; index++) {
141 encodedText += `%${bytes[index].toString(16).padStart(2, '0')}`;
142 }
143
144 return decodeURIComponent(encodedText);
145 }
146
147 private static base64ToBytes(base64: string): Uint8Array {
148 const binary = atob(base64);
149 const bytes = new Uint8Array(binary.length);
150 for (let index = 0; index < binary.length; index++) {
151 bytes[index] = binary.charCodeAt(index);
152 }
153 return bytes;
154 }
155
156 private static bytesToBase64(bytes: Uint8Array): string {
157 let binary = '';
158 for (let index = 0; index < bytes.byteLength; index++) {
159 binary += String.fromCharCode(bytes[index]);
160 }
161 return btoa(binary);
162 }
163}
讲解164 行
本地存储混淆加解密人工通读

UtilityEncrypt.ts

用自实现的 32 位混合哈希生成种子,再对 UTF-8 字节做循环异或,输出 ct 字段包成 JSON 的字符串。仅用于本地存档与配置的轻量混淆,md5 并非标准 MD5,不能用于密码或网络传输等安全场景。

先看 md5 与 getSeedBytes 的种子来源,再看 encrypt、decrypt 的字节换算与 ct 包装,最后看兼容旧接口的 aesEncrypt 与 aesDecrypt。

特殊处理与易错点

6注释轻量可逆加密工具。 设计目标:同步、跨平台、低依赖,只用于本地存储/配置混淆,不用于强安全场景。
7属性key(string):该模块的运行态字段。
8属性iv(string):该模块的运行态字段。
11注释UtilityEncrypt:轻量可逆加密工具。 设计目标:同步、跨平台、低依赖,只用于本地存储/配置混淆,不用于强安全场
12方法用四个初始常量对字符码做乘加与异或迭代,末轮混合后拼成四段十六进制。
38方法对字符串逐字符更新四个 32 位状态,再做末轮混合,输出 32 位小写十六进制串。
45方法把文本按 UTF-8 编码成字节,与种子流异或后转成 base64,再包进带 ct 字段的 JSON。
54方法从 ct 包装或纯 base64 中还原密文字节,异或同一 seed 流后按 UTF-8 解码。
64方法旧接口名,内部直接转调 encrypt,异常时打印日志后重新抛出。
76方法旧接口名,内部直接转调 decrypt,异常时打印日志后重新抛出。
85方法按字节循环,用种子流当前字节和位置混合值异或,返回等长的新字节数组。
98方法把 key 与 iv 用竖线拼接后取 md5,再把摘要字符串转成字节作为种子流。
107方法尝试解析为 JSON,取到字符串类型的 ct 字段就返回它,否则原样返回输入。
120方法用 encodeURIComponent 编码后逐字符解析百分号转义,得到 UTF-8 字节数组。
137方法把每个字节拼成百分号两位十六进制文本,再整体解码还原字符串。
147方法调用 atob 得到二进制字符串,再逐字符取字符码填入新字节数组。
156方法把字节逐个转成字符拼成二进制字符串,再调用 btoa 编码。