-
Notifications
You must be signed in to change notification settings - Fork 0
/
crypto_utils.ts
102 lines (86 loc) · 2.13 KB
/
crypto_utils.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
import { bytes, encodeBase64Url } from "./deps.ts";
export async function hmacSha256Digest(
crypto: SubtleCrypto,
secret: CryptoKey | ArrayBuffer,
body: BufferSource,
length?: number,
): Promise<ArrayBuffer> {
if (secret instanceof ArrayBuffer) {
secret = await crypto.importKey(
"raw",
secret,
{
name: "HMAC",
hash: "SHA-256",
},
false,
["sign"],
);
}
const result = await crypto.sign("HMAC", secret, body);
if (length !== null) return result.slice(0, length);
return result;
}
export function hkdfSha256Extract(
crypto: SubtleCrypto,
salt: ArrayBuffer,
ikm: ArrayBuffer,
) {
if (salt.byteLength === 0) {
salt = new Uint8Array(256).fill(0).buffer.slice(0);
}
return hmacSha256Digest(crypto, salt, ikm);
}
export async function hkdfSha256Expand(
crypto: SubtleCrypto,
prk: ArrayBuffer,
info: ArrayBuffer,
length: number,
) {
const infoBytes = new Uint8Array(info);
let t = new Uint8Array(0);
let okm = new Uint8Array(0);
let i = 0;
while (okm.byteLength < length) {
i++;
t = new Uint8Array(
await hmacSha256Digest(crypto, prk, bytes.concat([t, infoBytes])),
);
okm = bytes.concat([okm, t]);
}
return okm.slice(0, length);
}
export async function ecdh(
crypto: SubtleCrypto,
{ privateKey, publicKey }: CryptoKeyPair,
) {
const ecdhKey = await crypto.deriveKey(
{ name: "ECDH", public: publicKey },
privateKey,
{
name: "AES-GCM",
length: 256,
},
true,
["encrypt", "decrypt"],
);
return crypto.exportKey("raw", ecdhKey);
}
const encoder = new TextEncoder();
export async function forgeJwt(
key: CryptoKey,
// deno-lint-ignore no-explicit-any
payload: Record<string, any>,
{ crypto = globalThis.crypto.subtle }: { crypto?: SubtleCrypto } = {},
): Promise<string> {
const jwt = [{ typ: "JWT", alg: "ES256" }, payload].map((p) =>
encodeBase64Url(JSON.stringify(p))
).join(".");
const digest = await crypto.sign(
{ "name": "ECDSA", "hash": "SHA-256" },
key,
encoder.encode(jwt),
);
const signature = encodeBase64Url(digest);
return jwt + "." + signature;
}