UNPKG

3box

Version:
46 lines (35 loc) 1.11 kB
"use strict"; var nacl = require('tweetnacl'); nacl.util = require('tweetnacl-util'); var randomNonce = function randomNonce() { return nacl.randomBytes(24); }; var symEncryptBase = function symEncryptBase(msg, symKey, nonce) { nonce = nonce || randomNonce(); if (typeof msg === 'string') { msg = nacl.util.decodeUTF8(msg); } var ciphertext = nacl.secretbox(msg, nonce, symKey); return { nonce: nacl.util.encodeBase64(nonce), ciphertext: nacl.util.encodeBase64(ciphertext) }; }; var symDecryptBase = function symDecryptBase(ciphertext, symKey, nonce, toBuffer) { ciphertext = nacl.util.decodeBase64(ciphertext); nonce = nacl.util.decodeBase64(nonce); var cleartext = nacl.secretbox.open(ciphertext, nonce, symKey); if (toBuffer) { return cleartext ? Buffer.from(cleartext) : null; } return cleartext ? nacl.util.encodeUTF8(cleartext) : null; }; var newSymKey = function newSymKey() { return nacl.randomBytes(32); }; module.exports = { randomNonce: randomNonce, symEncryptBase: symEncryptBase, symDecryptBase: symDecryptBase, newSymKey: newSymKey };