/
aead.ts
77 lines (67 loc) · 2.71 KB
/
aead.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
/// SPDX-License-Identifier: MIT
/// SPDX-FileCopyrightText: Copyright © 2023 Tony Garnock-Jones <tonyg@leastfixedpoint.com>
import { Nonce } from './nonce';
export class AuthenticationFailure extends Error {}
export interface AEAD {
readonly NAME: string;
readonly KEYBYTES: number;
readonly NONCEBYTES: number;
readonly TAGBYTES: number;
encrypt_detached(plaintext: Uint8Array,
ciphertext: Uint8Array,
messagelength: number,
tag: Uint8Array,
key: DataView,
nonce: Nonce,
associated_data?: Uint8Array): void;
encrypt(plaintext: Uint8Array,
key: DataView,
nonce: Nonce,
associated_data?: Uint8Array): Uint8Array;
decrypt_detached(plaintext: Uint8Array,
ciphertext: Uint8Array,
messagelength: number,
expected_tag: Uint8Array,
key: DataView,
nonce: Nonce,
associated_data?: Uint8Array): boolean;
decrypt(ciphertextAndTag: Uint8Array,
key: DataView,
nonce: Nonce,
associated_data?: Uint8Array): Uint8Array;
}
export function _encrypt(this: AEAD,
plaintext: Uint8Array,
key: DataView,
nonce: Nonce,
associated_data?: Uint8Array): Uint8Array
{
const ciphertextAndTag = new Uint8Array(plaintext.byteLength + this.TAGBYTES);
this.encrypt_detached(plaintext,
ciphertextAndTag,
plaintext.byteLength,
ciphertextAndTag.subarray(plaintext.byteLength),
key,
nonce,
associated_data);
return ciphertextAndTag;
}
export function _decrypt(this: AEAD,
ciphertextAndTag: Uint8Array,
key: DataView,
nonce: Nonce,
associated_data?: Uint8Array): Uint8Array
{
const plaintext = new Uint8Array(ciphertextAndTag.byteLength - this.TAGBYTES);
if (!this.decrypt_detached(plaintext,
ciphertextAndTag,
plaintext.byteLength,
ciphertextAndTag.subarray(plaintext.byteLength),
key,
nonce,
associated_data)) {
throw new AuthenticationFailure("AEAD authentication failed");
}
return plaintext;
}
export { ChaCha20Poly1305_RFC8439 } from './aead/chacha20poly1305';