work.js 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. var SEA = require('./root');
  2. var shim = require('./shim');
  3. var S = require('./settings');
  4. var sha = require('./sha256');
  5. var u;
  6. SEA.work = SEA.work || (async (data, pair, cb, opt) => { try { // used to be named `proof`
  7. var salt = (pair||{}).epub || pair; // epub not recommended, salt should be random!
  8. var opt = opt || {};
  9. if(salt instanceof Function){
  10. cb = salt;
  11. salt = u;
  12. }
  13. data = (typeof data == 'string')? data : JSON.stringify(data);
  14. if('sha' === (opt.name||'').toLowerCase().slice(0,3)){
  15. var rsha = shim.Buffer.from(await sha(data, opt.name), 'binary').toString(opt.encode || 'base64')
  16. if(cb){ try{ cb(rsha) }catch(e){console.log(e)} }
  17. return rsha;
  18. }
  19. salt = salt || shim.random(9);
  20. var key = await (shim.ossl || shim.subtle).importKey('raw', new shim.TextEncoder().encode(data), {name: opt.name || 'PBKDF2'}, false, ['deriveBits']);
  21. var work = await (shim.ossl || shim.subtle).deriveBits({
  22. name: opt.name || 'PBKDF2',
  23. iterations: opt.iterations || S.pbkdf2.iter,
  24. salt: new shim.TextEncoder().encode(opt.salt || salt),
  25. hash: opt.hash || S.pbkdf2.hash,
  26. }, key, opt.length || (S.pbkdf2.ks * 8))
  27. data = shim.random(data.length) // Erase data in case of passphrase
  28. var r = shim.Buffer.from(work, 'binary').toString(opt.encode || 'base64')
  29. if(cb){ try{ cb(r) }catch(e){console.log(e)} }
  30. return r;
  31. } catch(e) {
  32. console.log(e);
  33. SEA.err = e;
  34. if(SEA.throw){ throw e }
  35. if(cb){ cb() }
  36. return;
  37. }});
  38. module.exports = SEA.work;