Skip to content

Instantly share code, notes, and snippets.

@dominictarr
Last active February 9, 2017 13:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dominictarr/66f1bec4a506e23c471a5b9befb2c415 to your computer and use it in GitHub Desktop.
Save dominictarr/66f1bec4a506e23c471a5b9befb2c415 to your computer and use it in GitHub Desktop.
example of how to read a fixed size binary prefix to a pull-stream
var Reader = require('pull-reader')
var box = require('./')
var pCont = require('pull-cont')
var randomBytes = require('crypto').randomBytes
var pull = require('pull-stream')
var Cat = require('pull-cat')
//key is 32 bytes and nonce is 24 bytes, written to start of stream.
exports.unbox = function UnboxStreamWithNonce (key) {
var reader = Reader(1000) //timeout, 1 second
//remember, a through pull-stream is a sink stream (takes a "read", calls it)
return function (read) {
reader(read)
//that returns a source stream, return a "read"
return pCont(function (cb) {
reader.read(24, function (err, nonce) {
if(err) return cb(err)
var source = function (abort, cb) {
if(abort) reader.abort(abort, cb)
else reader.read(null, cb)
}
cb(null, pull(source, box.createUnboxStream(key, nonce)))
})
})
}
}
exports.box = function (key) {
var nonce = randomBytes(24)
return function (read) {
return Cat([pull.values([nonce]), pull(read, box.createBoxStream(key, nonce))])
}
}
if(!module.parent) {
var crypto = require('crypto')
var toPull = require('stream-to-pull-stream')
var key = crypto.createHash('sha256').update(process.argv[3]).digest()
if(!exports[process.argv[2]]) throw new Error('usage: node example.js box|unbox {passwork}')
var through = exports[process.argv[2]](key)
pull(
toPull.source(process.stdin),
through,
toPull.sink(process.stdout)
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment