Skip to content

Commit

Permalink
Test for hash validity on verification
Browse files Browse the repository at this point in the history
  • Loading branch information
ranisalt committed Apr 5, 2016
1 parent b54fd4b commit fbc01bb
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 6 deletions.
16 changes: 10 additions & 6 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,10 @@ const defaults = Object.freeze({

const limits = Object.freeze(bindings.limits);

const isValidHash = hash => {
return /^\$argon2[di]\$m=\d+,t=\d+,p=\d+(?:\$[a-zA-Z0-9+\/]+){2}$/.test(hash);
};

const validate = (salt, options) => {
'use strict';

Expand Down Expand Up @@ -93,30 +97,30 @@ module.exports = {
verify(hash, plain) {
'use strict';

if (!Buffer.isBuffer(hash)) {
hash = new Buffer(hash);
if (!isValidHash(hash)) {
return Promise.reject(new Error('Invalid hash, must be generated by Argon2.'));
}

if (!Buffer.isBuffer(plain)) {
plain = new Buffer(plain);
}

return bindings.verify(hash, plain, /argon2d/.test(hash));
return bindings.verify(new Buffer(hash), plain, hash[7] === 'd');
},

verifySync(hash, plain) {
'use strict';

console.warn('The synchronous API is deprecated, use ES6 await instead.');

if (!Buffer.isBuffer(hash)) {
hash = new Buffer(hash);
if (!isValidHash(hash)) {
throw new Error('Invalid hash, must be generated by Argon2.');
}

if (!Buffer.isBuffer(plain)) {
plain = new Buffer(plain);
}

return bindings.verifySync(hash, plain, /argon2d/.test(hash));
return bindings.verifySync(new Buffer(hash), plain, hash[7] === 'd');
}
};
30 changes: 30 additions & 0 deletions test.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -578,6 +578,21 @@ t.test('async verify wrong password', t => {
});
}).catch(t.threw);

t.test('async verify invalid hash', t => {
'use strict';

t.plan(1);

return argon2.generateSalt().then(salt => {
return argon2.hash(password, salt).then(hash => {
/* cut just a piece of the hash making it invalid */
return argon2.verify(hash.slice(8), password).catch(err => {
t.match(err.message, /invalid hash.+generated by argon2/i);
});
});
});
}).catch(t.threw);

t.test('async verify with null in password', t => {
'use strict';

Expand Down Expand Up @@ -648,6 +663,21 @@ t.test('sync verify wrong password', t => {
});
}).catch(t.threw);

t.test('sync verify invalid hash', t => {
'use strict';

t.plan(1);

return argon2.generateSalt().then(salt => {
return argon2.hash(password, salt).then(hash => {
/* cut just a piece of the hash making it invalid */
t.throws(() => {
argon2.verifySync(hash.slice(8), password);
}, /invalid hash.+generated by argon2/i);
});
});
}).catch(t.threw);

t.test('sync verify with null in password', t => {
'use strict';

Expand Down

0 comments on commit fbc01bb

Please sign in to comment.