gun/sea/decrypt.js
Mark Nadal 638c2c3c23 have unbuild function wrap to prevent scope leaks & allow RETURN hehehe so I can reject @bmatusiak 's lS change O:) O:) I love you you're a hero!
later with @bmatusiak check sea.then for '../gun.js' vs '../' vs ...
note: src/index -> core.js
TODO: something about WebRTC candidates hitting ack decrement limits?
2024-01-17 10:13:00 -08:00

44 lines
1.5 KiB
JavaScript

;(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;
}());