Skip to content

Commit

Permalink
Merge pull request #42 from tj/nvw-binary-secrets
Browse files Browse the repository at this point in the history
Don't require "secret" key to be a string
  • Loading branch information
natevw committed Feb 17, 2022
2 parents 58727f3 + 7db51c8 commit 4409a44
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 2 deletions.
4 changes: 2 additions & 2 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ var crypto = require('crypto');

exports.sign = function(val, secret){
if ('string' != typeof val) throw new TypeError("Cookie value must be provided as a string.");
if ('string' != typeof secret) throw new TypeError("Secret string must be provided.");
if (null == secret) throw new TypeError("Secret key must be provided.");
return val + '.' + crypto
.createHmac('sha256', secret)
.update(val)
Expand All @@ -35,7 +35,7 @@ exports.sign = function(val, secret){

exports.unsign = function(input, secret){
if ('string' != typeof input) throw new TypeError("Signed cookie string must be provided.");
if ('string' != typeof secret) throw new TypeError("Secret string must be provided.");
if (null == secret) throw new TypeError("Secret key must be provided.");
var tentativeValue = input.slice(0, input.lastIndexOf('.')),
expectedInput = exports.sign(tentativeValue, secret),
expectedBuffer = Buffer.from(expectedInput),
Expand Down
13 changes: 13 additions & 0 deletions test/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,14 @@ describe('.sign(val, secret)', function(){
var val = cookie.sign('hello', 'luna');
val.should.not.equal('hello.DGDUkGlIkCzPz+C0B064FNgHdEjox7ch8tOBGslZ5QI');
})
it('should accept appropriately non-string secrets', function(){
var key = Buffer.from("A0ABBC0C", 'hex'),
val = cookie.sign('hello', key);
val.should.equal('hello.hIvljrKw5oOZtHHSq5u+MlL27cgnPKX77y7F+x5r1to');
(function () {
cookie.sign('unsupported', new Date());
}).should.throw();
})
})

describe('.unsign(val, secret)', function(){
Expand All @@ -30,4 +38,9 @@ describe('.unsign(val, secret)', function(){
cookie.unsign(val+'.garbage', pwd).should.be.false();
cookie.unsign(val+'garbage', pwd).should.be.false();
})
it('should accept non-string secrets', function(){
var key = Uint8Array.from([0xA0, 0xAB, 0xBC, 0x0C]),
val = cookie.unsign('hello.hIvljrKw5oOZtHHSq5u+MlL27cgnPKX77y7F+x5r1to', key);
val.should.equal('hello');
})
})

0 comments on commit 4409a44

Please sign in to comment.