Reputation: 166
I created a Symfony2 application using FOSUserBundle and FOSRestBundle. I'd like to connect other application with my Symfony application using rest api. I need to write the Symfony password encoder function in Javascript. Actually in PHP, it goes like:
$salt = "secret";
$password = "azerty";
$salted = $password.'{'.$salt.'}';
$digest = hash('sha512', $salted, true);
for ($i = 1; $i < 5000; $i++) {
$digest = hash('sha512', $digest.$salted, true);
}
$digest = base64_encode($digest);
return $digest;
In Javascript, I tried to use CryptoJS library. My code is:
var salt = 'secret',
password = 'azerty',
salted = password + '{' + salt + '}'
digest = CryptoJS.SHA512(salted);
for (var i=1; i<5000; i++) {
digest = CryptoJS.SHA512(digest+salted);
}
digest = digest.toString(CryptoJS.enc.Base64);
return digest;
But guess what ? It does not work and i don't know why. Can anyone help please ? :)
Regards, Colzak.
Upvotes: 1
Views: 753
Reputation: 166
Ok @timothymctim 's response helped me. Actually, I think it's an issue about character encoding. Here's a (strange) solution :
The PHP:
$salt = "secret";
$password = "azerty";
$salted = $password.'{'.$salt.'}';
$digest = hash('sha512', $salted, true);
for ($i = 1; $i < 5000; $i++) {
$digest = hash('sha512', utf8_encode($digest).$salted, true);
}
$digest = base64_encode($digest);
return $digest;
And the Javascript :
var salt = 'secret',
password = 'azerty',
salted = password + '{' + salt + '}'
digest = CryptoJS.SHA512(salted);
for (var i=1; i<5000; i++) {
digest = CryptoJS.SHA512(digest.toString(CryptoJS.enc.Latin1)+salted);
}
digest = digest.toString(CryptoJS.enc.Base64);
return digest;
I don't know what to think. Thanks anyway everybody who helped !
Upvotes: 2
Reputation: 205
It doesn't work because "[t]he hash you get back isn't a string yet. It's a WordArray object. When you use a WordArray object in a string context, it's automatically converted to a hex string." (source)
By using digest = CryptoJS.SHA512(digest+salted);
digest is converted into a hex string.
If you change your PHP code to
$salt = "secret";
$password = "azerty";
$salted = $password.'{'.$salt.'}';
$digest = hash('sha512', $salted, false);
for ($i = 1; $i < 5000; $i++) {
$digest = hash('sha512', $digest.$salted, false);
}
return $digest;
and return the digest as a hex string (digest + ''
or digest.toString(CryptoJS.enc.Hex)
will do) it will work.
I'm not sure how to change the JavaScript code to match the original PHP code though.
Upvotes: 0