decrypt.js 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. var SEA = require('./root');
  2. var shim = require('./shim');
  3. var S = require('./settings');
  4. var aeskey = require('./aeskey');
  5. SEA.decrypt = SEA.decrypt || (async (data, pair, cb, opt) => { try {
  6. opt = opt || {};
  7. var key = (pair||opt).epriv || pair;
  8. if(!key){
  9. pair = await SEA.I(null, {what: data, how: 'decrypt', why: opt.why});
  10. key = pair.epriv || pair;
  11. }
  12. var json = S.parse(data);
  13. var buf, bufiv, bufct; try{
  14. buf = shim.Buffer.from(json.s, opt.encode || 'base64');
  15. bufiv = shim.Buffer.from(json.iv, opt.encode || 'base64');
  16. bufct = shim.Buffer.from(json.ct, opt.encode || 'base64');
  17. var ct = await aeskey(key, buf, opt).then((aes) => (/*shim.ossl ||*/ shim.subtle).decrypt({ // Keeping aesKey scope as private as possible...
  18. name: opt.name || 'AES-GCM', iv: new Uint8Array(bufiv), tagLength: 128
  19. }, aes, new Uint8Array(bufct)));
  20. }catch(e){
  21. if('utf8' === opt.encode){ throw "Could not decrypt" }
  22. if(SEA.opt.fallback){
  23. opt.encode = 'utf8';
  24. return await SEA.decrypt(data, pair, cb, opt);
  25. }
  26. }
  27. var r = S.parse(new shim.TextDecoder('utf8').decode(ct));
  28. if(cb){ try{ cb(r) }catch(e){console.log(e)} }
  29. return r;
  30. } catch(e) {
  31. console.log(e);
  32. SEA.err = e;
  33. if(SEA.throw){ throw e }
  34. if(cb){ cb() }
  35. return;
  36. }});
  37. module.exports = SEA.decrypt;