'how to use extended ASCII instead of unicode in PHP

I have an application that is developed in visual fox pro in which I have an encryption method that I want to transfer to php code, the code is as follows:

FUNCTION Encrypt
 LPARAMETER text
 LOCAL KEY, TEXT, J, LETTER
 key = ')&H%$V1#@^+=?/><:MN*-'
 textText = SPACE(0)
 c = 1
 FOR j = 1 TO LEN(text)
      letter = MOD(ASC(SUBSTR(text, j, 1))+ASC(SUBSTR(key, c, 1)), 256)
      teXtoenc = teXtoenc+CHR(letter)
      c = c+1
      IF c>=LEN(password)
           c = 1
      ENDIF
 ENDFOR
 RETURN text
ENDFUNC

the transformation in php would be:

<?php
function Encripta($teXto){
    $clAve = ")&H%\$V1#@^+=?/><:MN*-";
    $teXtoenc = "";
    $c = 1;
    for($j = 0; $j < strlen($teXto); $j++){
        $leTra = (odr($teXto[$j]) + ord($clAve[$c])) % 256;
        $c ++;
        $teXtoenc .= chr($leTra);
        if($c >= strlen($clAve))
            $c = 1;
    }
    return $teXtoenc;
}
?>

but when executing the code in php the results of both methods are not the same, investigating I found that reason is because php works with Unicode and not extended ASCII



Solution 1:[1]

It's an off by one error... In VFP the first character has the index 1. The following code gives you the first character of the password string:

SUBSTR(key,1,1)

PHP is zero based. The following code gives you the first character of the password string:

$clAve[0]

You are initializing the index for the password ($clAve) with 1 instead of 0. Therefore you end up encoding (can't call this encrypting) with a different byte in PHP compared to VFP. Here's a working version in PHP:

function Encripta($teXto){
    $clAve = ")&H%\$V1#@^+=?/><:MN*-";
    $teXtoenc = "";
    $c = 0;
    for($j = 0; $j < strlen($teXto); $j++){
        $leTra = (ord($teXto[$j]) + ord($clAve[$c])) % 256;
        $c ++;
        $teXtoenc .= chr($leTra);
        if($c >= strlen($clAve))
            $c = 0;
    }
    return $teXtoenc;
}
?>

Where you wrote $c = 1; I changed this to $c = 0;. The remaining code is unchanged.

The way you could have found this yourself is by printing the value of both ord() calls in PHP and the ASC() calls in VFP. The result for PHP would have been:

72 38 / 111 72 / 108 37 / 97 36 

and in VFP it would have been

72 41 / 111 38 / 108 72 / 97 37

You notice how the second number, the character from the password, moved to the left in PHP, because you started with the second character in the string.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1