To convert this PHP code to JavaScript it does not take much if you already have the lib for SHA1 , just change the syntax and add the following function to your code:
function substr(str, pos, len) {
return str.substr(pos, len);
};
In JavaScript substr
is a prototype method of the String object, this means that instead of adding the string as the first parameter, you must call directly from the string. And this code is a "wedge" to look like PHP.
And the Array you should use a literal object in JavaScript, because although Arrays allow you to use any non-numeric key, it is not the correct way to use them.
return {
'A': SHA1($A),
'B': SHA1($B)
}
You can keep variables with the $
character as in PHP, however in JavaScript it is not required, but since it is a unicode character, and any unicode can be used to define variable, this will allow. But do not forget to add var
before them.
Arithmetic operations use the same characters in both languages.
The final code will be:
function substr(str, pos, len) {
return str.substr(pos, len);
};
function derivate($key, $iv, $x) {
var $sha1_a = SHA1($iv + substr($key, $x, 32));
var $sha1_b = SHA1(substr($key, 32 + $x, 16) + $iv + substr($key, 48 + $x, 16));
var $sha1_c = SHA1(substr($key, 64 + $x, 32) + $iv);
var $sha1_d = SHA1($iv + substr($key, 96 + $x, 32));
var $A = substr($sha1_a, 0, 8) + substr($sha1_b, 8, 12) + substr($sha1_c, 4, 12);
var $B = substr($sha1_a, 8, 12) + substr($sha1_b, 0, 8) + substr($sha1_c, 16, 4) + substr($sha1_d, 0, 8);
return {
'A': SHA1($A),
'B': SHA1($B)
};
}
If you're more comfortable with the notation-oriented JavaScript object you can remove the "wedge" and write the code this way:
function derivate($key, $iv, $x) {
var $sha1_a = SHA1($iv + $key.substr($x, 32));
var $sha1_b = SHA1($key.substr(32 + $x, 16) + $iv + $key.substr(48 + $x, 16));
var $sha1_c = SHA1($key.substr(64 + $x, 32) + $iv);
var $sha1_d = SHA1($iv + $key.substr(96 + $x, 32));
var $A = $sha1_a.substr(0, 8) + $sha1_b.substr(8, 12) + $sha1_c.substr(4, 12);
var $B = $sha1_a.substr(8, 12) + $sha1_b.substr(0, 8) + $sha1_c.substr(16, 4) + $sha1_d.substr(0, 8);
return {
'A': SHA1($A),
'B': SHA1($B)
};
}
A next step would be to remove the $
character from the variables, as I mentioned earlier, it will work with, but they are not necessary, as effectively nothing adds on besides aesthetics.