简体   繁体   中英

Converting a JavaScript function to PHP and it doesn’t produce the expected output

Here is the JavaScript function:

Decrypt2 = function (strIn, strKey) {
  var strOut = new String();
  lenIn = strIn.length;
  lenKey = strKey.length;
  var i = 0;
  var numA;
  var numB;
  while (i < lenIn) {
    numA = parseInt(strIn.substr(i, 2), 30);
    numB = parseInt(strIn.substr(i + 2, 2), 30);
    numKey = strKey.charCodeAt(i / 4 % lenKey);
    strOut += String.fromCharCode(numA - numB - numKey);
    i += 4;
  }
  return strOut;
};

And here is my attempt at converting the PHP function:

function Decrypt2($strIn, $strKey) {
  $strOut = '';
  $lenIn = strlen($strIn);
  $lenKey = strlen($strKey);
  $i = 0;
  $numA;
  $numB;
  while ($i < $lenIn)  {
    $numA = intval(substr($strIn,$i, 2), 30);
    $numB = intval(substr($strIn,$i + 2, 2), 30);
    $numKey = ord(substr($strKey,$i / 4 % $lenKey,1));
    $strOut .= chr($numA - $numB - $numKey);
    $i += 4;
  }
  return $strOut;
}

I though that this would work but it doesn't output my expected output.

Expected input

<xml><flash></flash></xml>

Expected output

ćÄ

Unexecpted output

ïùÇÄ—¢

I faced the similar task of translating encryption/decryption functions between languages.

I would recommend that you use brackets for all mathematical statements so that differences in operator priority between php and js do not introduce differences in the output.

For example, change $i / 4 % $lenKey to ($i / 4) % $lenKey

One other thing you should be aware of is that for very large numerical inputs, the php mod operator may produce NEGATIVE values, even if neither operator is negative. To work around this, you can use fmod instead.

Change $i / 4 % $lenKey to fmod($i / 4, $lenKey)

The division in strKey.charCodeAt(i / 4 % lenKey) , in the javascript code, is producing a float, which the modulus doesn't cast to integer.

The php modulus on the other hand does cast it (ie it's equivalent to Math.floor(i / 4) % lenKey ).

Probably makes no difference, though.

Javascript String.fromCharCode() is a int to UNICODE converter. PHP chr() is an int to ASCII converter. You have to use a method like mb_convert_encoding() in php to convert integers to UNICODE.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM