git ssb

1+

Dominic / ssb-keys



Tree: 6fbfd862e4a06d10ffbcf951f549e28ddf9fb345

Files: 6fbfd862e4a06d10ffbcf951f549e28ddf9fb345 / multi.js

2409 bytesRaw
1var u = require('./util')
2var ref = require('ssb-ref')
3var pb = require('private-box')
4var sodium = require('chloride')
5
6function isString (s) {
7 return 'string' === typeof s
8}
9
10function isObject (o) {
11 return o && 'object' === typeof o
12}
13
14function isKeypair (kp) {
15 return isObject(kp) && isString(kp.public) && isString(kp.private)
16}
17
18exports.box = function (msg, recipients) {
19
20 var asym = [], sym = []
21 recipients.forEach(function (e) {
22 if(ref.isFeed(e)) {
23 var pk= u.toBuffer(e)
24 console.log(pk, pk.length)
25 asym.push(
26 sodium.crypto_sign_ed25519_pk_to_curve25519(pk)
27 )
28 }
29 else {
30 var key = new Buffer(e, 'base64')
31 if(key.length == 32)
32 sym.push(key)
33 }
34 })
35
36 return pb.multibox(
37 new Buffer(JSON.stringify(msg), 'utf8'),
38 asym,
39 sym,
40 7
41 ).toString('base64')+'.box'
42
43}
44
45exports.unbox = function (msg, keys, keyring) {
46 if(isObject(msg.content)) return msg.content
47
48 var ctxt = new Buffer(msg.content.substring(0, msg.content.indexOf('.')), 'base64')
49
50 function parse (ptxt) {
51 console.log('ptxt', ptxt)
52 if(ptxt) return JSON.parse(ptxt)
53 }
54
55 function _unbox (key, max) {
56 console.log('_unbox', key, max)
57 if(isString(key)) {
58 var k = new Buffer(key, 'base64')
59 if(k.length === 33)
60 return parse(pb.decrypt_open_direct(ctxt, k))
61 else if(k.length == 32)
62 return parse(pb.decrypt_symmetric(ctxt, k, max))
63 }
64 else if(isKeypair(key)) {
65 var sk = sodium.crypto_sign_ed25519_sk_to_curve25519(u.toBuffer(key.private))
66 return parse(pb.decrypt(ctxt, sk, max))
67 }
68 }
69
70 // handle the array case here,
71 // else we'd be supporting recursive arrays as keys
72 // which is what I intended.
73 // (unintended effects are potential security leaks)
74
75 function unbox (key, max) {
76 if(!key) return
77 if(Array.isArray(key)) {
78 for(var i = 0; i < key.length; i++) {
79 var ptxt = _unbox(key[i], max)
80 if(ptxt) return ptxt
81 }
82 }
83 else
84 return _unbox(key, max)
85 }
86
87 if(!keyring)
88 return unbox(keys, 8)
89
90 console.log('unbox...', keys, keyring)
91 return (
92 // decrypt the message directly.
93 unbox(keyring[msg.key], 0) ||
94 // decrypt one-way msgs from author
95 unbox(keyring[msg.author], 5) ||
96 // decrypt two-way groups
97 unbox(keyring['*'], 3) ||
98 // decrypt normal direct recipients
99 unbox(keys, 8)
100 )
101}
102
103
104
105
106
107
108
109

Built with git-ssb-web