Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
async decrypt(ciphertext, key, aad = '')
{
if (!sodium) sodium = await SodiumPlus.auto();
let header = ciphertext.slice(0, 5);
if (!await Util.hashEquals(MAGIC_HEADER, header)) {
throw new CryptoOperationException('Invalid ciphertext header.');
}
let decoded = await Util.toBuffer(base64url.parse(ciphertext.slice(5)));
let hkdfSalt = decoded.slice(0, SALT_SIZE);
let ctrNonce = decoded.slice(
SALT_SIZE,
SALT_SIZE + NONCE_SIZE
);
let mac = decoded.slice(
SALT_SIZE + NONCE_SIZE,
SALT_SIZE + NONCE_SIZE + MAC_SIZE
);
let cipher = decoded.slice(SALT_SIZE + NONCE_SIZE + MAC_SIZE);
let macKey = await Util.HKDF(key, hkdfSalt, 'HMAC-SHA-384');
let recalc;
if (aad.length > 0) {
recalc = await Util.hmac(
'sha384',
{
if (!sodium) sodium = await SodiumPlus.auto();
let encKey = Buffer.alloc(32, 0);
if (Buffer.isBuffer(key)) {
key.copy(encKey, 0);
} else if (SymmetricKey.isSymmetricKey(key)) {
key.getRawKey().copy(encKey, 0);
} else {
throw new TypeError('Argument 1 must be a SymmetricKey');
}
let header = ciphertext.slice(0, 5);
if (!await Util.hashEquals(MAGIC_HEADER, header)) {
throw new CryptoOperationException('Invalid ciphertext header.');
}
let decoded = await Util.toBuffer(base64url.parse(ciphertext.slice(5)));
let nonce = decoded.slice(0, NONCE_SIZE);
let encrypted = decoded.slice(NONCE_SIZE);
if (aad.length >= 0) {
if (!Buffer.isBuffer(aad)) {
aad = await Util.toBuffer(aad);
}
aad = Buffer.concat([nonce, aad]);
} else {
aad = nonce;
}
let decrypted;
try {
decrypted = await sodium.crypto_aead_xchacha20poly1305_ietf_decrypt(
encrypted,