UNPKG

tweetsodium

Version:

libsodium sealed cryptobox using tweetnacl

73 lines (61 loc) 2.67 kB
(function (global, factory) { if (typeof define === "function" && define.amd) { define(["tweetnacl", "blakejs"], factory); } else if (typeof exports !== "undefined") { factory(require("tweetnacl"), require("blakejs")); } else { var mod = { exports: {} }; factory(global.tweetnacl, global.blakejs); global.index = mod.exports; } })(this, function (_tweetnacl, _blakejs) { 'use strict'; _tweetnacl = _interopRequireDefault(_tweetnacl); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var tweetSodium = module.exports; // Authenticated sealing only prepends the nonce to the ciphertext. Anonymous // sealing also prepends a random public key. tweetSodium.overheadLength = _tweetnacl.default.box.overheadLength + _tweetnacl.default.box.publicKeyLength; // Generates a 24 byte nonce that is a blake2b digest of the ephemeral // public key and the reipient's public key. // // Returns a 24-byte Uint8Array // // Parameters: // - epk - ephemeral public key Uint8Array // - publicKey - recipient's public key Uint8Array function sealNonce(epk, publicKey) { var hash = (0, _blakejs.blake2bInit)(_tweetnacl.default.box.nonceLength, false); (0, _blakejs.blake2bUpdate)(hash, epk); (0, _blakejs.blake2bUpdate)(hash, publicKey); return (0, _blakejs.blake2bFinal)(hash); } // Encrypt a message for a recipient. // // Returns a Uint8Array whose length is 48 bytes greater than the message's. // // Parameters: // - message - message Uint8Array to encrypt. // - publicKey - recipient's public key Uint8Array. tweetSodium.seal = function (message, publicKey) { var ekp = _tweetnacl.default.box.keyPair(); var out = new Uint8Array(message.length + tweetSodium.overheadLength); out.set(ekp.publicKey, 0); var nonce = sealNonce(ekp.publicKey, publicKey); var ct = _tweetnacl.default.box(message, nonce, publicKey, ekp.secretKey); out.set(ct, _tweetnacl.default.box.publicKeyLength); return out; }; // Decrypt the ciphertext message using the secret key. // // Returns a Uint8Array whose length is 48 bytes less than the ciphertext's. // // Parameters: // - ciphertext - encrypted message Uint8Array. // - secretKey - secret key Uint8Array. tweetSodium.sealOpen = function (ciphertext, publicKey, secretKey) { var epk = ciphertext.slice(0, _tweetnacl.default.box.publicKeyLength); var nonce = sealNonce(epk, publicKey); ciphertext = ciphertext.slice(_tweetnacl.default.box.publicKeyLength); return _tweetnacl.default.box.open(ciphertext, nonce, epk, secretKey); }; });