Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

add implementation

  • Loading branch information...
commit d6127bf3ac25eadf681149e53595f409e91aacc5 1 parent 865f267
@tj authored
View
42 index.js
@@ -1,2 +1,42 @@
-module.exports = require('./lib/cookie-signature');
+/**
+ * Module dependencies.
+ */
+
+var crypto = require('crypto');
+
+/**
+ * Sign the given `val` with `secret`.
+ *
+ * @param {String} val
+ * @param {String} secret
+ * @return {String}
+ * @api private
+ */
+
+exports.sign = function(val, secret){
+ if ('string' != typeof val) throw new TypeError('cookie required');
+ if ('string' != typeof secret) throw new TypeError('secret required');
+ return val + '.' + crypto
+ .createHmac('sha256', secret)
+ .update(val)
+ .digest('base64')
+ .replace(/\=+$/, '');
+};
+
+/**
+ * Unsign and decode the given `val` with `secret`,
+ * returning `false` if the signature is invalid.
+ *
+ * @param {String} val
+ * @param {String} secret
+ * @return {String|Boolean}
+ * @api private
+ */
+
+exports.unsign = function(val, secret){
+ if ('string' != typeof val) throw new TypeError('cookie required');
+ if ('string' != typeof secret) throw new TypeError('secret required');
+ var str = val.slice(0, val.lastIndexOf('.'));
+ return exports.sign(str, secret) == val ? str : false;
+};
View
0  lib/cookie-signature.js
No changes.
View
24 test/index.js
@@ -0,0 +1,24 @@
+
+/**
+ * Module dependencies.
+ */
+
+var cookie = require('..');
+
+describe('.sign(val, secret)', function(){
+ it('should sign the cookie', function(){
+ var val = cookie.sign('hello', 'tobiiscool');
+ val.should.equal('hello.DGDUkGlIkCzPz+C0B064FNgHdEjox7ch8tOBGslZ5QI');
+
+ var val = cookie.sign('hello', 'luna');
+ val.should.not.equal('hello.DGDUkGlIkCzPz+C0B064FNgHdEjox7ch8tOBGslZ5QI');
+ })
+})
+
+describe('.unsign(val, secret)', function(){
+ it('should unsign the cookie', function(){
+ var val = cookie.sign('hello', 'tobiiscool');
+ cookie.unsign(val, 'tobiiscool').should.equal('hello');
+ cookie.unsign(val, 'luna').should.be.false;
+ })
+})
Please sign in to comment.
Something went wrong with that request. Please try again.