-
Notifications
You must be signed in to change notification settings - Fork 0
/
bc.js
340 lines (261 loc) · 6.87 KB
/
bc.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
const libsodium = require('libsodium-wrappers');
const sodium = require('libsodium');
/**
* format
*
* format ciphertexts
*
* @param {String} ciphertext
* @param {String} nonce
* @api private
*
*/
function format(ciphertext, nonce) {
return ciphertext + '*' + nonce;
}
/**
* parse
*
* parse ciphertexts
*
* @param {String} input
* @api private
*
*/
function parse(input) {
if (typeof input !== 'string') { return [ input, null ]; }
var match = /([0-9a-f]+)\*([0-9a-f]{48})/.exec(input);
if (!match) { return [ input, null ]; }
return [ match[1], match[2] ];
}
/**
* sinit
*
* initialize the symmetric cabinet
*
* @param {Object} config
* @api private
*
*/
function sinit(config) {
config = config || {};
var k = config.key;
if (!k) { throw new Error('Symmetric key cabinet cannot be used without secret key.'); }
k = libsodium.from_hex(k);
function enc(m, done) {
var n = libsodium.randombytes_buf(sodium._crypto_secretbox_noncebytes());
var nout = libsodium.to_hex(n);
var c = libsodium.crypto_secretbox_easy(m, n, k, 'hex');
var cout = format(c, nout);
return (done) ? done(null, cout) : cout;
}
function dec(c, n, done) {
var cin = libsodium.from_hex(c);
var nin = libsodium.from_hex(n);
var m = libsodium.crypto_secretbox_open_easy(cin, nin, k, 'text');
return (done) ? done(null, m) : m;
}
return [enc, dec];
}
/**
* ainit
*
* initialize the asymmetric cabinet
*
* @param {Object} config
* @api private
*
*/
function ainit(config) {
config = config || {};
var sk = config.privateKey || config.secretKey || config.sk;
var pk = config.publicKey || config.pk;
if (!sk) { throw new Error('Asymmetric key cabinet cannot be used without private (secret) key.'); }
sk = libsodium.from_hex(sk);
if (!pk) { throw new Error('Asymmetric key cabinet cannot be used without public key.'); }
pk = libsodium.from_hex(pk);
if (libsodium.compare(libsodium.crypto_scalarmult_base(sk), pk) === 0) {
throw new Error('Invalid asymmetric key cabinet initialization: bound keypair.');
}
function enc(m, done) {
var n = libsodium.randombytes_buf(sodium._crypto_box_noncebytes());
var nout = libsodium.to_hex(n);
var c = libsodium.crypto_box_easy(m, n, pk, sk, 'hex');
var cout = format(c, nout);
return (done) ? done(null, cout) : cout;
}
function dec(c, n, done) {
var cin = libsodium.from_hex(c);
var nin = libsodium.from_hex(n);
var m = libsodium.crypto_box_open_easy(cin, nin, pk, sk, 'text');
return (done) ? done(null, m) : m;
}
return [enc, dec];
}
/**
* bc
*
* The main function, configures the cabinet and returns
* the middleware that adds it to the express req object.
*
* @param {String} name
* @param {Object} config
* @api public
*
*/
function bc(name, config) {
if (typeof name === 'object') {
config = name;
name = undefined;
}
config = config || {};
var registry = new Object();
if (config.symmetric) {
var [symE, symD] = sinit(config.symmetric);
registry['sym'] = { e: symE, d: symD };
}
if (config.asymmetric) {
var [asyE, asyD] = ainit(config.asymmetric);
registry['asy'] = { e: asyE, d: asyD };
}
var cabinets = Object.keys(registry);
if (cabinets.length < 1) { throw new Error('Configuration objects required for middleware.'); }
const direct = (cabinets.length === 1);
/**
* select
*
* select the cabinet to be used
* for the cryptographic operation
*
* @param {String} specified
* @api private
*
*/
function select(specified) {
// infer the type if in direct mode
type = specified || (direct && cabinets[0]);
if (!type || ['sym', 'asy'].indexOf(type) === -1) {
throw new Error('Please specify \'sym\' (symmetric) or \'asy\' (asymmetric) as the type.');
}
return type;
}
/**
* encrypt
*
* encrypt a message using the denoted cabinet
*
* @param {Object|String} arg
* @param {Function} done
* @api public
*
*/
function encrypt(arg, done) {
var type, message;
function _encrypt(message) {
// handle invalid arguments
if (!message) {
throw new Error('Unable to operate on an empty message.');
}
// if message is an object, stringify it
if (typeof message === 'object') {
message = JSON.stringify(message);
}
// prepare and launch the cryptographic operation
var launch = registry[type];
if (!launch) { throw new Error('Cabinet not initialized for type ' + type + '.'); }
return launch['e'](message, done);
}
function ehandle(err) {
if (!done) { throw err; }
return done(err);
}
try {
if (direct) {
type = select(); // infer type
message = arg;
return _encrypt(message);
} else {
type = select(arg); // send argument as type
function wrapped(message) {
try {
return _encrypt(message);
} catch (ex) {
return ehandle(ex);
}
}
return wrapped;
}
} catch (ex) {
ehandle(ex);
}
}
/**
* decrypt
*
* decrypt a message using the denoted cabinet
*
* @param {String} arg
* @param {String} opt
* @param {Function} done
* @api public
*
*/
function decrypt(arg, opt, done) {
if (opt && typeof opt === 'function') {
done = opt;
opt = undefined;
}
var type, message, nonce;
function _decrypt(message, nonce) {
if (!nonce) { [message, nonce] = parse(message); }
if (!message) {
throw new Error('Unable to operate on an empty message.');
}
if (!nonce) {
throw new Error('Unable to decrypt without nonce.');
}
// prepare and launch the cryptographic operation
var launch = registry[type];
if (!launch) { throw new Error('Cabinet not initialized for type ' + type + '.'); }
return launch['d'](message, nonce, done);
}
function ehandle(err) {
if (!done) { throw err; }
return done(err);
}
try {
if (direct) {
type = select(); // infer type
return _decrypt(arg, opt);
} else {
type = select(arg); // send argument as type
function wrapped(message, nonce) {
try {
return _decrypt(message, nonce);
} catch (ex) {
return ehandle(ex);
}
}
return wrapped;
}
} catch (ex) {
return ehandle(ex);
}
}
const cabinetNoir = { direct: direct, encrypt: encrypt, decrypt: decrypt };
return function(req, res, next) {
if (name) {
req[name] = cabinetNoir;
} else {
req.bc = cabinetNoir;
}
next();
};
}
exports = module.exports = bc;
exports.symkg = () => {
return { key: libsodium.crypto_secretbox_keygen('hex'), keyType: 'chacha20poly1305' };
};
exports.asykg = () => {
return libsodium.crypto_box_keypair('hex');
};