To convert this PHP code to Javascript it doesn’t take much if you already have the lib to 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 the substr
is a prototype method of the String object, which means that instead of adding as the first parameter to the string, you must call directly from the string. And this code is a "shim" to look like PHP.
And the Array should use a literal object in Javascript, because although Arrays allow use of 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 necessary, but as it is a Unicode character, and any Unicode can be used to define variable, this will allow. But don’t forget to add the var
before they do.
Arithmetic operations use the same characters in both languages.
The final code will remain:
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 are more comfortable with Javascript object oriented notation you can remove the "shim" 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 $
of the variables, as I mentioned earlier, will work with, but are not necessary, as effectively add nothing but aesthetics.
I edited the title to sound like not just a request, but something useful to the community.
– Guilherme Nascimento
Are you sure the question is not: "how to convert this code to JS"? Pq basically if vc write this function before your code:
var substr = function(str, pos, len) { return str.substr(pos, len); };
your code will work within the condition you have a lib to SHA1– Gabriel Gartz
@Gabrielgartz yes, this was the title but it was remanded by MODS
– Elaine
@Elaine personal opinion, I find your title better than the altered, put the code I wrote, worked?
– Gabriel Gartz