encrypt.js 995 B

12345678910111213141516171819202122232425262728293031
  1. var SEA = require('./root');
  2. var shim = require('./shim');
  3. var S = require('./settings');
  4. var aeskey = require('./aeskey');
  5. SEA.encrypt = async (data, pair, cb, opt) => { try {
  6. var opt = opt || {};
  7. const key = pair.epriv || pair;
  8. const msg = JSON.stringify(data)
  9. const rand = {s: shim.random(8), iv: shim.random(16)};
  10. const ct = await aeskey(key, rand.s, opt)
  11. .then((aes) => shim.subtle.encrypt({ // Keeping the AES key scope as private as possible...
  12. name: opt.name || 'AES-GCM', iv: new Uint8Array(rand.iv)
  13. }, aes, new shim.TextEncoder().encode(msg)))
  14. const r = 'SEA'+JSON.stringify({
  15. ct: shim.Buffer.from(ct, 'binary').toString('utf8'),
  16. iv: rand.iv.toString('utf8'),
  17. s: rand.s.toString('utf8')
  18. });
  19. if(cb){ try{ cb(r) }catch(e){console.log(e)} }
  20. return r;
  21. } catch(e) {
  22. SEA.err = e;
  23. if(cb){ cb() }
  24. return;
  25. }}
  26. module.exports = SEA.encrypt;