secret.js 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. var SEA = require('./root');
  2. var shim = require('./shim');
  3. var S = require('./settings');
  4. // Derive shared secret from other's pub and my epub/epriv
  5. SEA.secret = SEA.secret || (async (key, pair, cb, opt) => { try {
  6. opt = opt || {};
  7. if(!pair || !pair.epriv || !pair.epub){
  8. pair = await SEA.I(null, {what: key, how: 'secret', why: opt.why});
  9. }
  10. var pub = key.epub || key;
  11. var epub = pair.epub;
  12. var epriv = pair.epriv;
  13. var ecdhSubtle = shim.ossl || shim.subtle;
  14. var pubKeyData = keysToEcdhJwk(pub);
  15. var props = Object.assign({ public: await ecdhSubtle.importKey(...pubKeyData, true, []) },{name: 'ECDH', namedCurve: 'P-256'}); // Thanks to @sirpy !
  16. var privKeyData = keysToEcdhJwk(epub, epriv);
  17. var derived = await ecdhSubtle.importKey(...privKeyData, false, ['deriveBits']).then(async (privKey) => {
  18. // privateKey scope doesn't leak out from here!
  19. var derivedBits = await ecdhSubtle.deriveBits(props, privKey, 256);
  20. var rawBits = new Uint8Array(derivedBits);
  21. var derivedKey = await ecdhSubtle.importKey('raw', rawBits,{ name: 'AES-GCM', length: 256 }, true, [ 'encrypt', 'decrypt' ]);
  22. return ecdhSubtle.exportKey('jwk', derivedKey).then(({ k }) => k);
  23. })
  24. var r = derived;
  25. if(cb){ try{ cb(r) }catch(e){console.log(e)} }
  26. return r;
  27. } catch(e) {
  28. console.log(e);
  29. SEA.err = e;
  30. if(SEA.throw){ throw e }
  31. if(cb){ cb() }
  32. return;
  33. }});
  34. // can this be replaced with settings.jwk?
  35. var keysToEcdhJwk = (pub, d) => { // d === priv
  36. //var [ x, y ] = Buffer.from(pub, 'base64').toString('utf8').split(':') // old
  37. var [ x, y ] = pub.split('.') // new
  38. var jwk = d ? { d: d } : {}
  39. return [ // Use with spread returned value...
  40. 'jwk',
  41. Object.assign(
  42. jwk,
  43. { x: x, y: y, kty: 'EC', crv: 'P-256', ext: true }
  44. ), // ??? refactor
  45. {name: 'ECDH', namedCurve: 'P-256'}
  46. ]
  47. }
  48. module.exports = SEA.secret;