verify.js 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. // Copyright 2011 Joyent, Inc. All rights reserved.
  2. var assert = require('assert-plus');
  3. var crypto = require('crypto');
  4. ///--- Exported API
  5. module.exports = {
  6. /**
  7. * Simply wraps up the node crypto operations for you, and returns
  8. * true or false. You are expected to pass in an object that was
  9. * returned from `parse()`.
  10. *
  11. * @param {Object} parsedSignature the object you got from `parse`.
  12. * @param {String} key either an RSA private key PEM or HMAC secret.
  13. * @return {Boolean} true if valid, false otherwise.
  14. * @throws {TypeError} if you pass in bad arguments.
  15. */
  16. verifySignature: function verifySignature(parsedSignature, key) {
  17. assert.object(parsedSignature, 'parsedSignature');
  18. assert.string(key, 'key');
  19. var alg = parsedSignature.algorithm.match(/(HMAC|RSA|DSA)-(\w+)/);
  20. if (!alg || alg.length !== 3)
  21. throw new TypeError('parsedSignature: unsupported algorithm ' +
  22. parsedSignature.algorithm);
  23. if (alg[1] === 'HMAC') {
  24. var hmac = crypto.createHmac(alg[2].toUpperCase(), key);
  25. hmac.update(parsedSignature.signingString);
  26. return (hmac.digest('base64') === parsedSignature.params.signature);
  27. } else {
  28. var verify = crypto.createVerify(alg[0]);
  29. verify.update(parsedSignature.signingString);
  30. return verify.verify(key, parsedSignature.params.signature, 'base64');
  31. }
  32. }
  33. };