You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

51 lines
1.1 KiB

7 years ago
  1. /**
  2. * Module dependencies.
  3. */
  4. var crypto = require('crypto');
  5. /**
  6. * Sign the given `val` with `secret`.
  7. *
  8. * @param {String} val
  9. * @param {String} secret
  10. * @return {String}
  11. * @api private
  12. */
  13. exports.sign = function(val, secret){
  14. if ('string' != typeof val) throw new TypeError('cookie required');
  15. if ('string' != typeof secret) throw new TypeError('secret required');
  16. return val + '.' + crypto
  17. .createHmac('sha256', secret)
  18. .update(val)
  19. .digest('base64')
  20. .replace(/\=+$/, '');
  21. };
  22. /**
  23. * Unsign and decode the given `val` with `secret`,
  24. * returning `false` if the signature is invalid.
  25. *
  26. * @param {String} val
  27. * @param {String} secret
  28. * @return {String|Boolean}
  29. * @api private
  30. */
  31. exports.unsign = function(val, secret){
  32. if ('string' != typeof val) throw new TypeError('cookie required');
  33. if ('string' != typeof secret) throw new TypeError('secret required');
  34. var str = val.slice(0, val.lastIndexOf('.'))
  35. , mac = exports.sign(str, secret);
  36. return sha1(mac) == sha1(val) ? str : false;
  37. };
  38. /**
  39. * Private
  40. */
  41. function sha1(str){
  42. return crypto.createHash('sha1').update(str).digest('hex');
  43. }