gun/sea/encrypt.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

42 lines
1.5 KiB
JavaScript

;(function(){
var SEA = require('./root');
var shim = require('./shim');
var S = require('./settings');
var aeskey = require('./aeskey');
var u;
SEA.encrypt = SEA.encrypt || (async (data, pair, cb, opt) => { try {
opt = opt || {};
var key = (pair||opt).epriv || pair;
if(u === data){ throw '`undefined` not allowed.' }
if(!key){
if(!SEA.I){ throw 'No encryption key.' }
pair = await SEA.I(null, {what: data, how: 'encrypt', why: opt.why});
key = pair.epriv || pair;
}
var msg = (typeof data == 'string')? data : await shim.stringify(data);
var rand = {s: shim.random(9), iv: shim.random(15)}; // consider making this 9 and 15 or 18 or 12 to reduce == padding.
var ct = await aeskey(key, rand.s, opt).then((aes) => (/*shim.ossl ||*/ shim.subtle).encrypt({ // Keeping the AES key scope as private as possible...
name: opt.name || 'AES-GCM', iv: new Uint8Array(rand.iv)
}, aes, new shim.TextEncoder().encode(msg)));
var r = {
ct: shim.Buffer.from(ct, 'binary').toString(opt.encode || 'base64'),
iv: rand.iv.toString(opt.encode || 'base64'),
s: rand.s.toString(opt.encode || 'base64')
}
if(!opt.raw){ r = 'SEA' + await shim.stringify(r) }
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.encrypt;
}());