verify.js 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. var SEA = require('./root');
  2. var shim = require('./shim');
  3. var S = require('./settings');
  4. var sha256hash = require('./sha256');
  5. var parse = require('./parse');
  6. var u;
  7. SEA.verify = SEA.verify || (async (data, pair, cb) => { try {
  8. const json = parse(data)
  9. if(false === pair){ // don't verify!
  10. const raw = (json !== data)?
  11. (json.s && json.m)? parse(json.m) : data
  12. : json;
  13. if(cb){ try{ cb(raw) }catch(e){console.log(e)} }
  14. return raw;
  15. }
  16. const pub = pair.pub || pair
  17. const jwk = S.jwk(pub)
  18. const key = await (shim.ossl || shim.subtle).importKey('jwk', jwk, S.ecdsa.pair, false, ['verify'])
  19. const hash = await sha256hash(json.m)
  20. const sig = new Uint8Array(shim.Buffer.from(json.s, 'utf8'))
  21. const check = await (shim.ossl || shim.subtle).verify(S.ecdsa.sign, key, sig, new Uint8Array(hash))
  22. if(!check){ throw "Signature did not match." }
  23. const r = check? parse(json.m) : u;
  24. if(cb){ try{ cb(r) }catch(e){console.log(e)} }
  25. return r;
  26. } catch(e) {
  27. console.log(e);
  28. SEA.err = e;
  29. if(cb){ cb() }
  30. return;
  31. }});
  32. module.exports = SEA.verify;