encrypt.js 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. var SEA = require('./root');
  2. var shim = require('./shim');
  3. var S = require('./settings');
  4. var aeskey = require('./aeskey');
  5. var u;
  6. SEA.encrypt = SEA.encrypt || (async (data, pair, cb, opt) => { try {
  7. opt = opt || {};
  8. var key = (pair||opt).epriv || pair;
  9. if(u === data){ throw '`undefined` not allowed.' }
  10. if(!key){
  11. pair = await SEA.I(null, {what: data, how: 'encrypt', why: opt.why});
  12. key = pair.epriv || pair;
  13. }
  14. var msg = (typeof data == 'string')? data : JSON.stringify(data);
  15. var rand = {s: shim.random(9), iv: shim.random(15)}; // consider making this 9 and 15 or 18 or 12 to reduce == padding.
  16. var ct = await aeskey(key, rand.s, opt).then((aes) => (/*shim.ossl ||*/ shim.subtle).encrypt({ // Keeping the AES key scope as private as possible...
  17. name: opt.name || 'AES-GCM', iv: new Uint8Array(rand.iv)
  18. }, aes, new shim.TextEncoder().encode(msg)));
  19. var r = {
  20. ct: shim.Buffer.from(ct, 'binary').toString(opt.encode || 'base64'),
  21. iv: rand.iv.toString(opt.encode || 'base64'),
  22. s: rand.s.toString(opt.encode || 'base64')
  23. }
  24. if(!opt.raw){ r = 'SEA'+JSON.stringify(r) }
  25. if(cb){ try{ cb(r) }catch(e){console.log(e)} }
  26. return r;
  27. } catch(e) {
  28. console.log(e);
  29. SEA.err = e;
  30. if(SEA.throw){ throw e }
  31. if(cb){ cb() }
  32. return;
  33. }});
  34. module.exports = SEA.encrypt;