-
Notifications
You must be signed in to change notification settings - Fork 1
/
aead.js
70 lines (63 loc) · 1.99 KB
/
aead.js
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
/*
* Copyright (c) 2023, Alden Torres
*
* Licensed under the terms of the MIT license.
* Copy of the license at https://opensource.org/licenses/MIT
*/
import {
libecc,
} from "./util.js";
/**
* Encrypt a plaintext message using ChaCha20-Poly1305.
*
* See https://datatracker.ietf.org/doc/html/rfc8439
*
* @param {Uint8Array} plaintext the input message
* @param {Uint8Array} aad the associated additional authenticated data
* @param {Uint8Array} nonce public nonce, should never ever be reused with the same key, size:ecc_aead_chacha20poly1305_NONCESIZE
* @param {Uint8Array} key the secret key, size:ecc_aead_chacha20poly1305_KEYSIZE
* @return {Uint8Array} the encrypted form of the input
*/
export function aead_chacha20poly1305_encrypt(
plaintext,
aad,
nonce,
key,
) {
let out = new Uint8Array(plaintext.length + libecc.ecc_aead_chacha20poly1305_MACSIZE);
libecc.ecc_aead_chacha20poly1305_encrypt(
out,
plaintext, plaintext.length,
aad, aad.length,
nonce,
key,
);
return out;
}
/**
* Decrypt a ciphertext message using ChaCha20-Poly1305.
*
* See https://datatracker.ietf.org/doc/html/rfc8439
*
* @param {Uint8Array} ciphertext the input encrypted message
* @param {Uint8Array} aad the associated additional authenticated data
* @param {Uint8Array} nonce public nonce, should never ever be reused with the same key, size:ecc_aead_chacha20poly1305_NONCESIZE
* @param {Uint8Array} key the secret key, size:ecc_aead_chacha20poly1305_KEYSIZE
* @return {Uint8Array} the decrypted form of the input or null if the verification fails.
*/
export function aead_chacha20poly1305_decrypt(
ciphertext,
aad,
nonce,
key,
) {
let out = new Uint8Array(ciphertext.length - libecc.ecc_aead_chacha20poly1305_MACSIZE);
const r = libecc.ecc_aead_chacha20poly1305_decrypt(
out,
ciphertext, ciphertext.length,
aad, aad.length,
nonce,
key,
);
return r === 0 ? out : null;
}