pair.js 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. var SEA = require('./root');
  2. var shim = require('./shim');
  3. var S = require('./settings');
  4. var Buff = (typeof Buffer !== 'undefined')? Buffer : shim.Buffer;
  5. //SEA.pair = async (data, proof, cb) => { try {
  6. SEA.pair = SEA.pair || (async (cb) => { try {
  7. const ecdhSubtle = shim.ossl || shim.subtle
  8. // First: ECDSA keys for signing/verifying...
  9. var sa = await shim.subtle.generateKey(S.ecdsa.pair, true, [ 'sign', 'verify' ])
  10. .then(async (keys) => {
  11. // privateKey scope doesn't leak out from here!
  12. //const { d: priv } = await shim.subtle.exportKey('jwk', keys.privateKey)
  13. const key = {};
  14. key.priv = (await shim.subtle.exportKey('jwk', keys.privateKey)).d;
  15. const pub = await shim.subtle.exportKey('jwk', keys.publicKey)
  16. //const pub = Buff.from([ x, y ].join(':')).toString('base64') // old
  17. key.pub = pub.x+'.'+pub.y // new
  18. // x and y are already base64
  19. // pub is UTF8 but filename/URL safe (https://www.ietf.org/rfc/rfc3986.txt)
  20. // but split on a non-base64 letter.
  21. return key;
  22. })
  23. // To include PGPv4 kind of keyId:
  24. // const pubId = await SEA.keyid(keys.pub)
  25. // Next: ECDH keys for encryption/decryption...
  26. try{
  27. var dh = await ecdhSubtle.generateKey(S.ecdh, true, ['deriveKey'])
  28. .then(async (keys) => {
  29. // privateKey scope doesn't leak out from here!
  30. const key = {};
  31. key.epriv = (await ecdhSubtle.exportKey('jwk', keys.privateKey)).d;
  32. const pub = await ecdhSubtle.exportKey('jwk', keys.publicKey)
  33. //const epub = Buff.from([ ex, ey ].join(':')).toString('base64') // old
  34. key.epub = pub.x+'.'+pub.y // new
  35. // ex and ey are already base64
  36. // epub is UTF8 but filename/URL safe (https://www.ietf.org/rfc/rfc3986.txt)
  37. // but split on a non-base64 letter.
  38. return key;
  39. })
  40. }catch(e){
  41. if(SEA.window){ throw e }
  42. if(e == 'Error: ECDH is not a supported algorithm'){ console.log('Ignoring ECDH...') }
  43. else { throw e }
  44. } dh = dh || {};
  45. const r = { pub: sa.pub, priv: sa.priv, /* pubId, */ epub: dh.epub, epriv: dh.epriv }
  46. if(cb){ try{ cb(r) }catch(e){console.log(e)} }
  47. return r;
  48. } catch(e) {
  49. console.log(e);
  50. SEA.err = e;
  51. if(cb){ cb() }
  52. return;
  53. }});
  54. module.exports = SEA.pair;