pair.js 2.6 KB

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