-
Notifications
You must be signed in to change notification settings - Fork 1
/
hash.ts
113 lines (102 loc) · 2.41 KB
/
hash.ts
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
import { encode } from 'https://deno.land/std@0.143.0/encoding/hex.ts';
import { decode } from 'https://deno.land/std@0.179.0/encoding/base64.ts';
export async function hashString(
algorithm: 'SHA-1' | 'SHA-256' | 'SHA-512',
d: string | Uint8Array,
): Promise<string> {
const data = typeof d === 'string' ? new TextEncoder().encode(d) : d;
const hashRes = new Uint8Array(
await crypto.subtle.digest(
algorithm,
data,
),
);
return hexString(hashRes);
}
/**
* 将二进制数据储存为 HEX (16 进制字符串)
* @param data 二进制数据
* @returns HEX (16 进制字符串)
*/
export function hexString(data: Uint8Array): string {
let s = '';
for (const d of encode(data)) {
s += String.fromCodePoint(d);
}
return s;
}
export async function hmac(
key: {
hash: 'SHA-1' | 'SHA-256' | 'SHA-512';
/** secret key */
s: string | Uint8Array;
} | CryptoKey,
/** data */
d: string | Uint8Array,
): Promise<Uint8Array> {
const textEncoder = new TextEncoder();
let cryptoKey: CryptoKey;
if (key instanceof CryptoKey) {
cryptoKey = key;
} else {
const { s, hash } = key;
const keyData = typeof s === 'string' ? textEncoder.encode(s) : s;
cryptoKey = await crypto.subtle.importKey(
'raw',
keyData,
{ name: 'HMAC', hash },
true,
['sign', 'verify'],
);
}
const data = typeof d === 'string' ? textEncoder.encode(d) : d;
const res = new Uint8Array(
await crypto.subtle.sign(
'HMAC',
cryptoKey,
data,
),
);
return res;
}
/**
* Sign data with RSA
* - only pkcs8
* - only RSASSA-PKCS1-v1_5
* @param key
* @param d
* @returns
*/
export async function rasSign(
key: {
hash: 'SHA-256' | 'SHA-512';
/** secret key */
s: string | Uint8Array;
} | CryptoKey,
/** data */
d: string | Uint8Array,
): Promise<Uint8Array> {
let cryptoKey: CryptoKey;
if (key instanceof CryptoKey) {
cryptoKey = key;
} else {
const { s, hash } = key;
const keyData = typeof s === 'string' ? decode(s) : s;
cryptoKey = await crypto.subtle.importKey(
'pkcs8',
keyData,
{ name: 'RSASSA-PKCS1-v1_5', hash: { name: hash } },
true,
['sign'],
);
}
const data = typeof d === 'string' ? new TextEncoder().encode(d) : d;
const res = new Uint8Array(
await crypto.subtle.sign(
'RSASSA-PKCS1-v1_5',
cryptoKey,
data,
),
);
return res;
}