Skip to content

Instantly share code, notes, and snippets.

@tychota
Created November 21, 2019 00:48
Show Gist options
  • Save tychota/88b4268dea82370f086945e492cb1410 to your computer and use it in GitHub Desktop.
Save tychota/88b4268dea82370f086945e492cb1410 to your computer and use it in GitHub Desktop.
const crypto = require("crypto");
const key = crypto.randomBytes(32);
const nonce = crypto.randomBytes(12);
const opts = { authTagLength: 16 };
const cipher = crypto.createCipheriv("chacha20-poly1305", key, nonce, opts);
const plaintext = "Hello World, il se fait tard ce soir.";
const aad = crypto.randomBytes(5);
cipher.setAAD(aad, { plaintextLength: Buffer.byteLength(plaintext) });
const ciphertext = cipher.update(plaintext, "utf8");
cipher.final();
const tag = cipher.getAuthTag();
// Now transmit { ciphertext, nonce, tag }.
console.log(ciphertext, nonce, tag);
const decipher = crypto.createDecipheriv("chacha20-poly1305", key, nonce, opts);
decipher.setAuthTag(tag);
decipher.setAAD(aad, { plaintextLength: ciphertext.length });
const receivedPlaintext = decipher.update(ciphertext, null, "utf8");
console.log(receivedPlaintext);
try {
decipher.final();
} catch (err) {
console.error("Authentication failed!");
return;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment