Colzak Colzak - 5 months ago 53
Javascript Question

Symfony2 password encoder function in Javascript

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.

Answer

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 !