-
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
decrypt.js
44 lines (40 loc) · 1.52 KB
/
decrypt.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
;(function(){
var SEA = require('./root');
var shim = require('./shim');
var S = require('./settings');
var aeskey = require('./aeskey');
SEA.decrypt = SEA.decrypt || (async (data, pair, cb, opt) => { try {
opt = opt || {};
var key = (pair||opt).epriv || pair;
if(!key){
if(!SEA.I){ throw 'No decryption key.' }
pair = await SEA.I(null, {what: data, how: 'decrypt', why: opt.why});
key = pair.epriv || pair;
}
var json = await S.parse(data);
var buf, bufiv, bufct; try{
buf = shim.Buffer.from(json.s, opt.encode || 'base64');
bufiv = shim.Buffer.from(json.iv, opt.encode || 'base64');
bufct = shim.Buffer.from(json.ct, opt.encode || 'base64');
var ct = await aeskey(key, buf, opt).then((aes) => (/*shim.ossl ||*/ shim.subtle).decrypt({ // Keeping aesKey scope as private as possible...
name: opt.name || 'AES-GCM', iv: new Uint8Array(bufiv), tagLength: 128
}, aes, new Uint8Array(bufct)));
}catch(e){
if('utf8' === opt.encode){ throw "Could not decrypt" }
if(SEA.opt.fallback){
opt.encode = 'utf8';
return await SEA.decrypt(data, pair, cb, opt);
}
}
var r = await S.parse(new shim.TextDecoder('utf8').decode(ct));
if(cb){ try{ cb(r) }catch(e){console.log(e)} }
return r;
} catch(e) {
console.log(e);
SEA.err = e;
if(SEA.throw){ throw e }
if(cb){ cb() }
return;
}});
module.exports = SEA.decrypt;
}());