git ssb

1+

Dominic / ssb-secret-blob



Tree: d25e99c8d7d2425a42b646de802ebef08774082a

Files: d25e99c8d7d2425a42b646de802ebef08774082a / index.js

2968 bytesRaw
1var path = require('path')
2var BoxStream = require('pull-box-stream')
3var File = require('pull-file')
4var pull = require('pull-stream')
5var toPull = require('stream-to-pull-stream')
6//var Hash = require('pull-hash')
7var crypto = require('crypto')
8var zeros = new Buffer(24); zeros.fill(0)
9
10function Hash (cb) {
11 var hash = crypto.createHash('sha256')
12 var buffers = []
13 var hasher = pull.drain(function (data) {
14 data = 'string' === typeof data ? new Buffer(data) : data
15 buffers.push(data)
16 hash.update(data)
17 }, function (err) {
18 cb(err, buffers, hash.digest())
19 })
20 return hasher
21}
22
23exports.box =
24exports.encrypt =
25 function (key) {
26 return BoxStream.box(key, zeros)
27 }
28
29exports.unbox =
30exports.decrypt =
31 function (key) {
32 return BoxStream.unbox(key, zeros)
33 }
34
35if(!module.parent) {
36 var opts = require('minimist')(process.argv.slice(2))
37 var cmd = opts._.shift()
38
39 var blob = opts._.shift()
40
41 require('ssb-client')(function (err, sbot) {
42 if(err) throw err
43
44 if(/^(encrypt|box)$/.test(cmd)) {
45
46 //normally I would encourage stream users to always stream and
47 //not buffer inbetween processing stages, but crypto is sometimes
48 //an exception. here we need to hash something twice, first,
49 //hash the plain text to use as the key. This has the benefit
50 //of encrypting deterministically - the same file will have the same hash.
51 //this can be used to deduplicate storage, but has privacy implications.
52
53 //I do it here just because it's early days and this makes testing
54 //easier.
55 pull(File(blob), Hash(function (err, buffers, key) {
56
57 pull(
58 pull.once(Buffer.concat(buffers)),
59 BoxStream.createBoxStream(key, zeros),
60 //get the hash of the blob to be added.
61 //it would be better if muxrpc called back with the id,
62 //but that isn't implemented yet.
63 Hash(function (err, buffers, hash) {
64 if(err) throw err
65 var id = '&'+hash.toString('base64')+'.sha256'
66
67 pull(
68 pull.values(buffers),
69 sbot.blobs.add(id, function (err) {
70 if(err) throw err
71 console.log(id+'#'+key.toString('base64'))
72 sbot.close()
73 })
74 )
75
76 })
77 )
78 }))
79 }
80 else if(/^(decrypt|unbox)$/.test(cmd)) {
81 var id = blob.split('#')[0]
82 var key = new Buffer(blob.split('#')[1], 'base64')
83 sbot.blobs.want(id, function (err, has) {
84 if(err) throw err
85 if(!has) {
86 console.error('could not retrive blob:'+id)
87 return sbot.close()
88 }
89 console.error('has:'+id)
90 pull(
91 sbot.blobs.get(id),
92 BoxStream.createUnboxStream(key, zeros),
93 toPull.sink(process.stdout, function (err) {
94 sbot.close()
95 })
96 )
97 })
98 }
99 else {
100 sbot.close()
101 console.log('USAGE:')
102 }
103 })
104}
105
106

Built with git-ssb-web