crypto.ts
11.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
/**
* 摘要 / MAC 算法 helper。零运行时依赖:MD5 / SHA1 / SHA256 都是纯实现,HMAC 有 Web Crypto
* (异步)与纯实现(同步)两条路。
*
* 之所以放在 api-core 而不是各域:签名算法是「接入适配」的公共基建,且 web 子应用与原生
* 小程序都要用。Web Crypto 在现代浏览器 / Node 18+ 可用,但原生小程序没有 crypto.subtle,
* 因此 HMAC 另提供 hmacSha256Sync,签名器可按运行环境选择。
*/
/**
* MD5(RFC 1321)。
*
* 部分老链路用 MD5 加签(注意:glsx 系 RPC 网关实际是 SHA1,见 signers.ts),这里不引第三方包:
* catalog 里只有 RSA 链路用到 jsrsasign,为一个摘要算法再加一份依赖不值当。
* 实现按 32 位有符号整数走,输出小端 16 进制,
* 已用 RFC 1321 的测试向量核对。
*/
const SHIFT = [
7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14,
20, 5, 9, 14, 20, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 6, 10, 15, 21, 6,
10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21,
];
const K = Array.from({ length: 64 }, (_, i) => Math.floor(Math.abs(Math.sin(i + 1)) * 2 ** 32));
function toUtf8Bytes(input: string): number[] {
const bytes: number[] = [];
for (let i = 0; i < input.length; i += 1) {
let code = input.charCodeAt(i);
if (code < 0x80) {
bytes.push(code);
} else if (code < 0x800) {
bytes.push(0xc0 | (code >> 6), 0x80 | (code & 0x3f));
} else if (code < 0xd800 || code >= 0xe000) {
bytes.push(0xe0 | (code >> 12), 0x80 | ((code >> 6) & 0x3f), 0x80 | (code & 0x3f));
} else {
i += 1;
code = 0x10000 + (((code & 0x3ff) << 10) | (input.charCodeAt(i) & 0x3ff));
bytes.push(
0xf0 | (code >> 18),
0x80 | ((code >> 12) & 0x3f),
0x80 | ((code >> 6) & 0x3f),
0x80 | (code & 0x3f),
);
}
}
return bytes;
}
function rotateLeft(value: number, amount: number): number {
return (value << amount) | (value >>> (32 - amount));
}
function hexLittleEndian(word: number): string {
let out = '';
for (let i = 0; i < 4; i += 1) {
out += ((word >>> (i * 8)) & 0xff).toString(16).padStart(2, '0');
}
return out;
}
export function md5(input: string): string {
const message = toUtf8Bytes(input);
const bitLength = message.length * 8;
message.push(0x80);
while (message.length % 64 !== 56) message.push(0);
message.push(
bitLength & 0xff,
(bitLength >>> 8) & 0xff,
(bitLength >>> 16) & 0xff,
(bitLength >>> 24) & 0xff,
);
message.push(
Math.floor(bitLength / 2 ** 32) & 0xff,
Math.floor(bitLength / 2 ** 40) & 0xff,
Math.floor(bitLength / 2 ** 48) & 0xff,
Math.floor(bitLength / 2 ** 56) & 0xff,
);
let a = 0x67452301;
let b = 0xefcdab89;
let c = 0x98badcfe;
let d = 0x10325476;
for (let offset = 0; offset < message.length; offset += 64) {
const words: number[] = [];
for (let i = 0; i < 16; i += 1) {
const p = offset + i * 4;
words.push(
(message[p]! |
(message[p + 1]! << 8) |
(message[p + 2]! << 16) |
(message[p + 3]! << 24)) >>>
0,
);
}
let A = a;
let B = b;
let C = c;
let D = d;
for (let i = 0; i < 64; i += 1) {
let F: number;
let g: number;
if (i < 16) {
F = (B & C) | (~B & D);
g = i;
} else if (i < 32) {
F = (D & B) | (~D & C);
g = (5 * i + 1) % 16;
} else if (i < 48) {
F = B ^ C ^ D;
g = (3 * i + 5) % 16;
} else {
F = C ^ (B | ~D);
g = (7 * i) % 16;
}
F = (F + A + K[i]! + words[g]!) | 0;
A = D;
D = C;
C = B;
B = (B + rotateLeft(F, SHIFT[i]!)) | 0;
}
a = (a + A) | 0;
b = (b + B) | 0;
c = (c + C) | 0;
d = (d + D) | 0;
}
return hexLittleEndian(a) + hexLittleEndian(b) + hexLittleEndian(c) + hexLittleEndian(d);
}
/**
* HMAC-SHA256(Web Crypto,异步)。返回 64 位小写 hex。
* 异步是为了不引入 crypto-js 这类同步重依赖;调用方(dispatcher)已对签名做了 await。
*/
export async function hmacSha256(message: string, secret: string): Promise<string> {
const subtle = globalThis.crypto?.subtle;
if (!subtle) {
throw new Error(
'hmacSha256: 当前环境无 crypto.subtle(老版小程序基础库?),请改用 createSigner 注入同步算法(如 crypto-js)。',
);
}
const enc = new TextEncoder();
const key = await subtle.importKey(
'raw',
enc.encode(secret),
{ name: 'HMAC', hash: 'SHA-256' },
false,
['sign'],
);
const signature = await subtle.sign('HMAC', key, enc.encode(message));
return Array.from(new Uint8Array(signature))
.map((b) => b.toString(16).padStart(2, '0'))
.join('');
}
/**
* SHA1(RFC 3174)。
*
* 原生小程序(points-mall / store-assistant / business-assistant / scrm-carlife)与 web points
* 子应用的 glsx RPC 网关**都走 SHA1 加签**(`sha1(secret + 拼接原文 + secret).toUpperCase()`),
* 差别只在 web 侧 timestamp 也进签名原文。为不让 mp 重新造轮子,这里提供零依赖纯实现,
* 与 MD5 共用 `toUtf8Bytes`,并已用 RFC 3174 测试向量及真实抓包 golden 值核对。
*/
function leftRotate32(value: number, amount: number): number {
return ((value << amount) | (value >>> (32 - amount))) >>> 0;
}
function toHexBigEndian(word: number): string {
return (word >>> 0).toString(16).padStart(8, '0');
}
export function sha1(input: string): string {
const bytes = toUtf8Bytes(input);
const bitLen = bytes.length * 8;
bytes.push(0x80);
while (bytes.length % 64 !== 56) bytes.push(0);
// 64 位大端长度;本场景 message 远小于 2^32 位,高 32 位恒为 0。
const hi = Math.floor(bitLen / 2 ** 32);
const lo = bitLen >>> 0;
bytes.push(
(hi >>> 24) & 0xff,
(hi >>> 16) & 0xff,
(hi >>> 8) & 0xff,
hi & 0xff,
(lo >>> 24) & 0xff,
(lo >>> 16) & 0xff,
(lo >>> 8) & 0xff,
lo & 0xff,
);
let h0 = 0x67452301;
let h1 = 0xefcdab89;
let h2 = 0x98badcfe;
let h3 = 0x10325476;
let h4 = 0xc3d2e1f0;
const w = new Array<number>(80);
for (let i = 0; i < bytes.length; i += 64) {
for (let j = 0; j < 16; j += 1) {
const p = i + j * 4;
w[j] =
((bytes[p]! << 24) | (bytes[p + 1]! << 16) | (bytes[p + 2]! << 8) | bytes[p + 3]!) >>> 0;
}
for (let j = 16; j < 80; j += 1) {
w[j] = leftRotate32(w[j - 3]! ^ w[j - 8]! ^ w[j - 14]! ^ w[j - 16]!, 1);
}
let a = h0;
let b = h1;
let c = h2;
let d = h3;
let e = h4;
for (let j = 0; j < 80; j += 1) {
let f: number;
let k: number;
if (j < 20) {
f = (b & c) | (~b & d);
k = 0x5a827999;
} else if (j < 40) {
f = b ^ c ^ d;
k = 0x6ed9eba1;
} else if (j < 60) {
f = (b & c) | (b & d) | (c & d);
k = 0x8f1bbcdc;
} else {
f = b ^ c ^ d;
k = 0xca62c1d6;
}
const temp = (leftRotate32(a, 5) + f + e + k + w[j]!) | 0;
e = d;
d = c;
c = leftRotate32(b, 30);
b = a;
a = temp >>> 0;
}
h0 = (h0 + a) | 0;
h1 = (h1 + b) | 0;
h2 = (h2 + c) | 0;
h3 = (h3 + d) | 0;
h4 = (h4 + e) | 0;
}
return [h0, h1, h2, h3, h4].map(toHexBigEndian).join('');
}
/**
* SHA-256(FIPS 180-4)。GSC 网关的头部签名走 HMAC-SHA256,而原生小程序没有 Web Crypto,
* 故提供纯实现;与 MD5 / SHA1 共用 `toUtf8Bytes`,已用 NIST 向量核对。
*/
const SHA256_K = [
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2,
];
function rotateRight(value: number, amount: number): number {
return ((value >>> amount) | (value << (32 - amount))) >>> 0;
}
function sha256Bytes(message: number[]): number[] {
const bytes = message.slice();
const bitLen = bytes.length * 8;
bytes.push(0x80);
while (bytes.length % 64 !== 56) bytes.push(0);
const hi = Math.floor(bitLen / 2 ** 32);
const lo = bitLen >>> 0;
bytes.push(
(hi >>> 24) & 0xff,
(hi >>> 16) & 0xff,
(hi >>> 8) & 0xff,
hi & 0xff,
(lo >>> 24) & 0xff,
(lo >>> 16) & 0xff,
(lo >>> 8) & 0xff,
lo & 0xff,
);
let h0 = 0x6a09e667;
let h1 = 0xbb67ae85;
let h2 = 0x3c6ef372;
let h3 = 0xa54ff53a;
let h4 = 0x510e527f;
let h5 = 0x9b05688c;
let h6 = 0x1f83d9ab;
let h7 = 0x5be0cd19;
const w = new Array<number>(64);
for (let i = 0; i < bytes.length; i += 64) {
for (let j = 0; j < 16; j += 1) {
const p = i + j * 4;
w[j] =
((bytes[p]! << 24) | (bytes[p + 1]! << 16) | (bytes[p + 2]! << 8) | bytes[p + 3]!) >>> 0;
}
for (let j = 16; j < 64; j += 1) {
const x = w[j - 15]!;
const y = w[j - 2]!;
const s0 = rotateRight(x, 7) ^ rotateRight(x, 18) ^ (x >>> 3);
const s1 = rotateRight(y, 17) ^ rotateRight(y, 19) ^ (y >>> 10);
w[j] = (w[j - 16]! + s0 + w[j - 7]! + s1) >>> 0;
}
let a = h0;
let b = h1;
let c = h2;
let d = h3;
let e = h4;
let f = h5;
let g = h6;
let h = h7;
for (let j = 0; j < 64; j += 1) {
const S1 = rotateRight(e, 6) ^ rotateRight(e, 11) ^ rotateRight(e, 25);
const ch = (e & f) ^ (~e & g);
const temp1 = (h + S1 + ch + SHA256_K[j]! + w[j]!) | 0;
const S0 = rotateRight(a, 2) ^ rotateRight(a, 13) ^ rotateRight(a, 22);
const maj = (a & b) ^ (a & c) ^ (b & c);
const temp2 = (S0 + maj) | 0;
h = g;
g = f;
f = e;
e = (d + temp1) | 0;
d = c;
c = b;
b = a;
a = (temp1 + temp2) | 0;
}
h0 = (h0 + a) | 0;
h1 = (h1 + b) | 0;
h2 = (h2 + c) | 0;
h3 = (h3 + d) | 0;
h4 = (h4 + e) | 0;
h5 = (h5 + f) | 0;
h6 = (h6 + g) | 0;
h7 = (h7 + h) | 0;
}
const hash = [h0, h1, h2, h3, h4, h5, h6, h7];
const digest: number[] = [];
for (let i = 0; i < hash.length; i += 1) {
const word = hash[i]!;
digest.push((word >>> 24) & 0xff, (word >>> 16) & 0xff, (word >>> 8) & 0xff, word & 0xff);
}
return digest;
}
export function sha256(input: string): string {
return sha256Bytes(toUtf8Bytes(input))
.map((b) => b.toString(16).padStart(2, '0'))
.join('');
}
/**
* HMAC-SHA256(同步纯实现,RFC 2104)。返回 64 位小写 hex,与 crypto-js
* `HmacSHA256(msg, key).toString()` 一致;原生小程序用这个,web / Node 可用上面的异步版。
*/
export function hmacSha256Sync(message: string, secret: string): string {
const blockSize = 64;
let key = toUtf8Bytes(secret);
if (key.length > blockSize) key = sha256Bytes(key);
while (key.length < blockSize) key.push(0);
const inner = key.map((b) => b ^ 0x36).concat(toUtf8Bytes(message));
const outer = key.map((b) => b ^ 0x5c).concat(sha256Bytes(inner));
return sha256Bytes(outer)
.map((b) => b.toString(16).padStart(2, '0'))
.join('');
}