|
1 |
| -export async function hxEncrypt(data: Uint8Array, key: CryptoKey, tag?: Uint8Array): Promise<Uint8Array> { |
2 |
| - const iv = crypto.getRandomValues(new Uint8Array(12)) // AES-GCM requires a 12-byte IV |
3 |
| - if (!tag) { |
4 |
| - tag = crypto.getRandomValues(new Uint8Array(16)) |
5 |
| - } |
| 1 | +const tagLength = 128 |
| 2 | +const authenticating_default = new Uint8Array() |
6 | 3 |
|
| 4 | +export async function hxEncrypt(data: Uint8Array, key: CryptoKey, authenticating: Uint8Array = authenticating_default): Promise<Uint8Array> { |
| 5 | + const iv = crypto.getRandomValues(new Uint8Array(12)) // AES-GCM requires a 12-byte IV |
7 | 6 | const encrypted = await crypto.subtle.encrypt(
|
8 | 7 | {
|
9 | 8 | name: 'AES-GCM',
|
10 | 9 | iv,
|
11 |
| - tagLength: 128, |
12 |
| - additionalData: tag, |
| 10 | + tagLength, |
| 11 | + additionalData: authenticating, |
13 | 12 | },
|
14 | 13 | key,
|
15 | 14 | data,
|
16 | 15 | )
|
17 | 16 |
|
18 | 17 | const encryptedArray = new Uint8Array(encrypted)
|
19 |
| - const combined = new Uint8Array(iv.length + encryptedArray.length + tag.length) |
| 18 | + const combined = new Uint8Array(iv.length + encryptedArray.length) |
20 | 19 | combined.set(iv)
|
21 | 20 | combined.set(encryptedArray, iv.length)
|
22 |
| - combined.set(tag, encryptedArray.length + iv.length) |
23 | 21 | return combined
|
24 | 22 | }
|
25 | 23 |
|
26 |
| -export async function hxDecrypt(data: Uint8Array, key: CryptoKey): Promise<Uint8Array> { |
27 |
| - // The data layout of the combined representation is nonce, ciphertext, then tag. |
28 |
| - // The nonce is 12 bytes, the tag is 16 bytes, and the ciphertext is the rest of the data. |
| 24 | +export async function hxDecrypt(data: Uint8Array, key: CryptoKey, authenticating: Uint8Array = authenticating_default): Promise<Uint8Array> { |
29 | 25 | const iv = data.slice(0, 12) // nonce is the first 12 bytes
|
30 |
| - const encrypted = data.slice(12) // The ciphertext is everything between the nonce and the tag. |
31 |
| - // const tag = data.slice(-16) // The authentication tag has a length of 16 bytes. |
32 |
| - console.log({ iv, encrypted, data }) |
33 |
| - |
| 26 | + const encrypted = data.slice(12) // ciphertext and tag of 128 bits |
34 | 27 | const decrypted = await crypto.subtle.decrypt({
|
35 | 28 | name: 'AES-GCM',
|
36 | 29 | iv,
|
37 |
| - // tagLength: 32, // tag.length * 8, |
38 |
| - additionalData: new Uint8Array(), |
| 30 | + tagLength, |
| 31 | + additionalData: authenticating, |
39 | 32 | }, key, encrypted)
|
40 | 33 | return new Uint8Array(decrypted)
|
41 | 34 | }
|
0 commit comments