work.js 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. var SEA = require('./root');
  2. var shim = require('./shim');
  3. var S = require('./settings');
  4. var u;
  5. SEA.work = async (data, pair, cb) => { try { // used to be named `proof`
  6. var salt = pair.epub || pair; // epub not recommended, salt should be random!
  7. if(salt instanceof Function){
  8. cb = salt;
  9. salt = u;
  10. }
  11. salt = salt || shim.random(9);
  12. if (SEA.window) {
  13. // For browser subtle works fine
  14. const key = await shim.subtle.importKey(
  15. 'raw', new shim.TextEncoder().encode(data), { name: 'PBKDF2' }, false, ['deriveBits']
  16. )
  17. const result = await shim.subtle.deriveBits({
  18. name: 'PBKDF2',
  19. iterations: S.pbkdf2.iter,
  20. salt: new shim.TextEncoder().encode(salt),
  21. hash: S.pbkdf2.hash,
  22. }, key, S.pbkdf2.ks * 8)
  23. data = shim.random(data.length) // Erase data in case of passphrase
  24. const r = shim.Buffer.from(result, 'binary').toString('utf8')
  25. if(cb){ try{ cb(r) }catch(e){console.log(e)} }
  26. return r;
  27. }
  28. // For NodeJS crypto.pkdf2 rocks
  29. const crypto = shim.crypto;
  30. const hash = crypto.pbkdf2Sync(
  31. data,
  32. new shim.TextEncoder().encode(salt),
  33. S.pbkdf2.iter,
  34. S.pbkdf2.ks,
  35. S.pbkdf2.hash.replace('-', '').toLowerCase()
  36. )
  37. data = shim.random(data.length) // Erase passphrase for app
  38. const r = hash && hash.toString('utf8')
  39. if(cb){ try{ cb(r) }catch(e){console.log(e)} }
  40. return r;
  41. } catch(e) {
  42. SEA.err = e;
  43. if(cb){ cb() }
  44. return;
  45. }}
  46. module.exports = SEA.work;