sign.js 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. var SEA = require('./root');
  2. var shim = require('./shim');
  3. var S = require('./settings');
  4. var sha = 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. if(u === data){ throw '`undefined` not allowed.' }
  12. var json = S.parse(data);
  13. var check = opt.check = opt.check || json;
  14. if(SEA.verify && (SEA.opt.check(check) || (check && check.s && check.m))
  15. && u !== await SEA.verify(check, pair)){ // don't sign if we already signed it.
  16. var r = S.parse(check);
  17. if(!opt.raw){ r = 'SEA'+JSON.stringify(r) }
  18. if(cb){ try{ cb(r) }catch(e){console.log(e)} }
  19. return r;
  20. }
  21. var pub = pair.pub;
  22. var priv = pair.priv;
  23. var jwk = S.jwk(pub, priv);
  24. var hash = await sha(json);
  25. var sig = await (shim.ossl || shim.subtle).importKey('jwk', jwk, {name: 'ECDSA', namedCurve: 'P-256'}, false, ['sign'])
  26. .then((key) => (shim.ossl || shim.subtle).sign({name: 'ECDSA', hash: {name: 'SHA-256'}}, key, new Uint8Array(hash))) // privateKey scope doesn't leak out from here!
  27. var r = {m: json, s: shim.Buffer.from(sig, 'binary').toString(opt.encode || 'base64')}
  28. if(!opt.raw){ r = 'SEA'+JSON.stringify(r) }
  29. if(cb){ try{ cb(r) }catch(e){console.log(e)} }
  30. return r;
  31. } catch(e) {
  32. console.log(e);
  33. SEA.err = e;
  34. if(SEA.throw){ throw e }
  35. if(cb){ cb() }
  36. return;
  37. }});
  38. module.exports = SEA.sign;