I'm using Crypto to hash a string with salt 200 times. I had a weird behavior where the hash would always be the same. I now have it returning what appears to be proper results, but I'm wondering if someone can tell me why.
This is the original code that yields the same hash every time (assuming the same salt):
const crypto = require('crypto');
console.log(hashPwd('abc', '11111111111111111111111111111111'));
console.log(hashPwd('def', '11111111111111111111111111111111'));
function hashPwd(password, hexSalt){
var salt = hex2a(hexSalt);
var hashPwd = crypto.createHash('sha256').update(salt + password);
for(var x =0; x < 199; x++){
hashPwd = crypto.createHash('sha256').update(salt + hashPwd);
}
return hashPwd.digest('hex');
}
//From: http://stackoverflow.com/questions/3745666/how-to-convert-from-hex-to-ascii-in-javascript
function hex2a(hexx) {
var hex = hexx.toString();//force conversion
var str = '';
for (var i = 0; i < hex.length; i += 2)
str += String.fromCharCode(parseInt(hex.substr(i, 2), 16));
return str;
}
The above output yields:
52cfd2b127266c1c846ded37c986d8663506118332437daa6eadbc32525c2aa4
52cfd2b127266c1c846ded37c986d8663506118332437daa6eadbc32525c2aa4
While the following code returns the expected results:
const crypto = require('crypto');
console.log(hashPwd('abc', '11111111111111111111111111111111'));
console.log(hashPwd('def', '11111111111111111111111111111111'));
function hashPwd(password, hexSalt){
const hasher = crypto.createHash('sha256');
var salt = hex2a(hexSalt);
var hashPwd = hasher.update(salt + password);
for(var x =0; x < 199; x++){
hashPwd = hasher.update(salt + hashPwd);
}
return hashPwd.digest('hex');
}
//From: http://stackoverflow.com/questions/3745666/how-to-convert-from-hex-to-ascii-in-javascript
function hex2a(hexx) {
var hex = hexx.toString();//force conversion
var str = '';
for (var i = 0; i < hex.length; i += 2)
str += String.fromCharCode(parseInt(hex.substr(i, 2), 16));
return str;
}
Yields the proper:
05525f74c0220924a2c9626ca75c2d997bf8b49a8c74208501aaf7a222d11899
c846cb3dc58163530b7b7afc7b467c104fa11566f405b333d030e5e6595bfaec
Can someone please explain why?