Created
May 10, 2017 00:30
-
-
Save therebelrobot/13cae9e75c0dc3bf973ff84b3935b483 to your computer and use it in GitHub Desktop.
NACL SecretBox example (safely symm encrypt/decrypt)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const nacl = require('tweetnacl') | |
nacl.util = require('tweetnacl-util') | |
const crypto = require('crypto') | |
const key64 = '4jYJgju0rVSVSBBhihogB7dIW5UIEDhPHxwl+WJlfOk=' | |
const keyBuff = Buffer.from(key64, 'base64') | |
/* -------------- */ | |
/* Build jwt */ | |
/* -------------- */ | |
const nonceBuff = crypto.randomBytes(24) | |
const nonce64 = nonceBuff.toString('base64') | |
const args = process.argv | |
args.shift() | |
args.shift() | |
const message = args.length ? args.join(' ') : 'This is a super secret message.' | |
const messageBuff = new Buffer(message) | |
const box = nacl.secretbox( | |
messageBuff, | |
nonceBuff, | |
keyBuff) | |
const box64 = nacl.util.encodeBase64(box) | |
const msg = {box64, nonce64} | |
console.log(msg) | |
/* -------------- */ | |
/* Get from msg */ | |
/* -------------- */ | |
const msgNonceBuff = nacl.util.decodeBase64(msg.nonce64) | |
const msgBoxBuff = nacl.util.decodeBase64(msg.box64) | |
const msgMessageBuff = nacl.secretbox.open(msgBoxBuff, msgNonceBuff, keyBuff) | |
const msgMessage = nacl.util.encodeUTF8(msgMessageBuff) | |
console.log(msgMessage) | |
/* -------------- */ | |
/* Create new key */ | |
/* -------------- */ | |
console.log('') | |
console.log('POC Successful! Generating new keys for future use:') | |
console.log('') | |
console.log(crypto.randomBytes(32).toString('base64')) | |
console.log(crypto.randomBytes(32).toString('base64')) | |
console.log(crypto.randomBytes(32).toString('base64')) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment