-
-
Notifications
You must be signed in to change notification settings - Fork 144
Expand file tree
/
Copy pathtest_crypto_subtle_wrap_unwrap.ts
More file actions
66 lines (58 loc) · 1.87 KB
/
Copy pathtest_crypto_subtle_wrap_unwrap.ts
File metadata and controls
66 lines (58 loc) · 1.87 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
// Regression test for `crypto.subtle.wrapKey` / `unwrapKey` —
// generate two AES-GCM CryptoKeys, wrap the first with the second
// (AES-GCM wrap, since AES-KW is also supported but jose uses
// AES-GCM under the hood for A256GCMKW), unwrap, then confirm the
// recovered key decrypts a previously-encrypted ciphertext.
async function main() {
// 1) Generate the "real" key (the one we'll wrap).
const innerKey = await crypto.subtle.generateKey(
{ name: "AES-GCM", length: 256 },
true,
["encrypt", "decrypt"],
);
// 2) Generate the wrapping/KEK key.
const kek = await crypto.subtle.generateKey(
{ name: "AES-GCM", length: 256 },
true,
["wrapKey", "unwrapKey"],
);
// 3) Encrypt a plaintext with the inner key — we'll decrypt with
// the recovered key to confirm round-tripping preserved the bytes.
const iv = new Uint8Array(12);
crypto.getRandomValues(iv);
const plaintext = new TextEncoder().encode("hello wrap/unwrap");
const ct = await crypto.subtle.encrypt(
{ name: "AES-GCM", iv },
innerKey,
plaintext,
);
// 4) Wrap the inner key with the KEK (AES-GCM wrap).
const wrapIv = new Uint8Array(12);
crypto.getRandomValues(wrapIv);
const wrapped = await crypto.subtle.wrapKey(
"raw",
innerKey,
kek,
{ name: "AES-GCM", iv: wrapIv },
);
// 5) Unwrap to recover an AES-GCM CryptoKey.
const recovered = await crypto.subtle.unwrapKey(
"raw",
wrapped,
kek,
{ name: "AES-GCM", iv: wrapIv },
{ name: "AES-GCM", length: 256 },
true,
["encrypt", "decrypt"],
);
// 6) Decrypt the original ciphertext with the recovered key.
const pt = await crypto.subtle.decrypt(
{ name: "AES-GCM", iv },
recovered,
ct,
);
const decoded = new TextDecoder().decode(new Uint8Array(pt));
console.log(decoded);
console.log(decoded === "hello wrap/unwrap" ? "OK" : "FAIL");
}
main();