work.js 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  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. salt = salt || shim.random(9);
  14. if('SHA-256' === opt.name){
  15. var rsha = shim.Buffer.from(await sha(data), 'binary').toString('utf8')
  16. if(cb){ try{ cb(rsha) }catch(e){console.log(e)} }
  17. return rsha;
  18. }
  19. const key = await (shim.ossl || shim.subtle).importKey(
  20. 'raw', new shim.TextEncoder().encode(data), { name: opt.name || 'PBKDF2' }, false, ['deriveBits']
  21. )
  22. const result = await (shim.ossl || shim.subtle).deriveBits({
  23. name: opt.name || 'PBKDF2',
  24. iterations: opt.iterations || S.pbkdf2.iter,
  25. salt: new shim.TextEncoder().encode(opt.salt || salt),
  26. hash: opt.hash || S.pbkdf2.hash,
  27. }, key, opt.length || (S.pbkdf2.ks * 8))
  28. data = shim.random(data.length) // Erase data in case of passphrase
  29. const r = shim.Buffer.from(result, 'binary').toString('utf8')
  30. if(cb){ try{ cb(r) }catch(e){console.log(e)} }
  31. return r;
  32. } catch(e) {
  33. SEA.err = e;
  34. if(cb){ cb() }
  35. return;
  36. }});
  37. module.exports = SEA.work;