Skip to content

Commit

Permalink
timingSafeEqual: final === check and type checking
Browse files Browse the repository at this point in the history
  • Loading branch information
jsha committed Feb 19, 2016
1 parent 1af1602 commit 5840d64
Showing 1 changed file with 8 additions and 1 deletion.
9 changes: 8 additions & 1 deletion lib/crypto.js
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,9 @@ Hmac.prototype._transform = Hash.prototype._transform;
//
// Note: hmac object can not be used after validate() method has been called.
Hmac.prototype.validate = function(inputBuffer) {
if (!(inputBuffer instanceof Buffer)) {
throw new TypeError('Argument should be a Buffer');
}
var ah = new Hmac('sha256', this.key).update(this.digest()).digest();
var bh = new Hmac('sha256', this.key).update(inputBuffer).digest();
return ah.equals(bh);
Expand Down Expand Up @@ -687,7 +690,11 @@ function filterDuplicates(names) {
exports.timingSafeEqual = function(a, b) {
var key = randomBytes(32);
var ah = new Hmac('sha256', key).update(a);
return ah.validate(new Hmac('sha256', key).update(b).digest());
// The final === test is just in case of the vanishingly small chance of
// a collision. It only fires if the digest comparison passes and so doesn't
// leak timing information.
return ah.validate(new Hmac('sha256', key).update(b).digest()) &&
a.toString() === b.toString();
};

// Legacy API
Expand Down

0 comments on commit 5840d64

Please sign in to comment.