Reputation: 196
I would like to replicate the following PHP code in JS:
$salted = $raw_pass."{".$salt."}";
$iterations = 5000;
$digest = hash('sha512', $salted, true);
// "stretch" hash
for ($i = 0; $i < $iterations; $i++) {
$digest = hash('sha512', $digest.$salted, true);
}
return base64_encode($digest);
It's creating a hash from pass and salt, 5000 iterations. This is actually from Symfony's MessageDigestPasswordEncoder (I changed the code a bit for the sake of example, sorry for possible typos).
I want to replicate this in JavaScript and I did this:
var salted = raw_pass + "{" + salt + "}"
var digest = CryptoJS.SHA512(salted);
for (var i=0;i<5000;i++){
digest = CryptoJS.SHA512(digest+salted);
}
user.password = CryptoJS.enc.Base64.stringify(digest)
Everything works ok when I create digest
(I get the same string on both sides), but after it reiterates, I get different hashes. The symfony side is working, so the problem is somewhere in this JS.
What am I doing wrong?
Later edit:
I think I have an idea why this is not working. digest
is an object and salted
is a string. CryptoJS.SHA512 accepts both, but I don't think digest + salted
is not what is expecting.
Upvotes: 0
Views: 241
Reputation: 663
Why don't you just use PBKDF2 since CryptoJS also provides that, it seems.
Upvotes: 0
Reputation: 196
I could not fix it so I had to change the strategy. Considering I'm encoding already encoded (and salted) data and I'm not providing the whole info to the user, I should be safe.
I changed to SHA1 and I'm using btoa()
and atobe()
JS functions.
Upvotes: 0
Reputation: 288680
I think the problem is that in PHP you initialize the loop in 1
:
for ($i = 1; $i < $iterations; $i++)
but in JavaScript you initialize the loop in 0
:
for (var i=0;i<5000;i++)
Upvotes: 3
Reputation: 1278
I think a problem is in here:
<?php
$salted = $raw_pass."{"$salt."}";
?>
You forgot a dot ( . ), it should be this:
<?php
$salted = $raw_pass."{".$salt."}";
?>
Also you start one time with 1 and one time with 0 (see post below)
Upvotes: 0