Repositorio del curso CCOM4030 el semestre B91 del proyecto kilometro0

index.js 1.2KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  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 value must be provided as a string.");
  15. if ('string' != typeof secret) throw new TypeError("Secret string must be provided.");
  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("Signed cookie string must be provided.");
  33. if ('string' != typeof secret) throw new TypeError("Secret string must be provided.");
  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. }