sign.js 1.1 KB

1234567891011121314151617181920212223242526272829303132
  1. var SEA = require('./root');
  2. var shim = require('./shim');
  3. var S = require('./settings');
  4. var sha256hash = require('./sha256');
  5. var u;
  6. SEA.sign = SEA.sign || (async (data, pair, cb, opt) => { try {
  7. opt = opt || {};
  8. if(!(pair||opt).priv){
  9. pair = await SEA.I(null, {what: data, how: 'sign', why: opt.why});
  10. }
  11. const pub = pair.pub
  12. const priv = pair.priv
  13. const jwk = S.jwk(pub, priv)
  14. const hash = await sha256hash(JSON.stringify(data))
  15. const sig = await (shim.ossl || shim.subtle).importKey('jwk', jwk, S.ecdsa.pair, false, ['sign'])
  16. .then((key) => (shim.ossl || shim.subtle).sign(S.ecdsa.sign, key, new Uint8Array(hash))) // privateKey scope doesn't leak out from here!
  17. const r = 'SEA'+JSON.stringify({m: data, s: shim.Buffer.from(sig, 'binary').toString(opt.encode || 'base64')});
  18. if(cb){ try{ cb(r) }catch(e){console.log(e)} }
  19. return r;
  20. } catch(e) {
  21. console.log(e);
  22. SEA.err = e;
  23. if(SEA.throw){ throw e }
  24. if(cb){ cb() }
  25. return;
  26. }});
  27. module.exports = SEA.sign;