Symfony2 password encoder function in Javascript

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-11 11:06:58

问题


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.


回答1:


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 !




回答2:


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.



来源:https://stackoverflow.com/questions/25928509/symfony2-password-encoder-function-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!