Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.