gscSignature.js
1.96 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
import CryptoJS from "crypto-js";
function collectSignatureParams(data = {}, params = {}) {
const result = {};
const keys = new Set([...Object.keys(data), ...Object.keys(params)]);
keys.forEach((key) => {
const fromParams = Object.prototype.hasOwnProperty.call(params, key);
const value = fromParams ? params[key] : data[key];
if (value === null || value === undefined) {
return;
}
if (typeof value === "string") {
result[key] = fromParams ? value : JSON.stringify(value);
} else if (typeof value === "object") {
result[key] = JSON.stringify(value);
} else {
result[key] = String(value);
}
});
return result;
}
export function createGscNonce() {
if (typeof crypto !== "undefined" && crypto.getRandomValues) {
const bytes = new Uint8Array(16);
crypto.getRandomValues(bytes);
bytes[6] = (bytes[6] & 0x0F) | 0x40;
bytes[8] = (bytes[8] & 0x3F) | 0x80;
const hex = Array.from(bytes, byte => byte.toString(16).padStart(2, "0")).join("");
return [
hex.slice(0, 8),
hex.slice(8, 12),
hex.slice(12, 16),
hex.slice(16, 20),
hex.slice(20),
].join("-");
}
return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (character) => {
const random = Math.floor(Math.random() * 16);
const value = character === "x" ? random : (random & 0x3) | 0x8;
return value.toString(16);
});
}
export function createGscSignature(options) {
const systemHeaders = {
"X-App-Id": options.appId,
"X-Nonce": options.nonce || createGscNonce(),
"X-Timestamp": String(options.timestamp || Date.now()),
};
const signParams = {
...systemHeaders,
...collectSignatureParams(options.data, options.params),
};
const noSignAttr = options.noSignAttr || [];
const source = Object.keys(signParams)
.sort()
.filter(key => !noSignAttr.includes(key))
.map(key => `${key}=${signParams[key]}`)
.join("&");
return {
...systemHeaders,
"X-Sign": CryptoJS.HmacSHA256(
`${source}&secret=${options.appSecret}`,
options.appSecret,
).toString(),
};
}