sign.js 1.2 KB

123456789101112131415161718192021222324252627282930313233343536
  1. var SEA = require('./root');
  2. var shim = require('./shim');
  3. var S = require('./settings');
  4. var sha256hash = require('./sha256');
  5. SEA.sign = async (data, pair, cb) => { try {
  6. if(data.slice
  7. && 'SEA{' === data.slice(0,4)
  8. && '"m":' === data.slice(4,8)){
  9. // TODO: This would prevent pair2 signing pair1's signature.
  10. // So we may want to change this in the future.
  11. // but for now, we want to prevent duplicate double signature.
  12. if(cb){ try{ cb(data) }catch(e){console.log(e)} }
  13. return data;
  14. }
  15. const pub = pair.pub
  16. const priv = pair.priv
  17. const jwk = S.jwk(pub, priv)
  18. const msg = JSON.stringify(data)
  19. const hash = await sha256hash(msg)
  20. const sig = await shim.subtle.importKey('jwk', jwk, S.ecdsa.pair, false, ['sign'])
  21. .then((key) => shim.subtle.sign(S.ecdsa.sign, key, new Uint8Array(hash))) // privateKey scope doesn't leak out from here!
  22. const r = 'SEA'+JSON.stringify({m: msg, s: shim.Buffer.from(sig, 'binary').toString('utf8')});
  23. if(cb){ try{ cb(r) }catch(e){console.log(e)} }
  24. return r;
  25. } catch(e) {
  26. console.log(e);
  27. SEA.err = e;
  28. if(cb){ cb() }
  29. return;
  30. }}
  31. module.exports = SEA.sign;