pair.js 2.7 KB

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