PHP: Methods to encrypt and decrypt with private key (part 3)


Please read
PHP: Methods to encrypt and decrypt with private key (part 1)

PHP: Methods to encrypt and decrypt with private key (part 2)

Method 3: use xor encryption

function _tutorialspots_3($str, $key)
{
    $length = strlen($key);
    for ($i = 0; $i < strlen($str); $i++) {
        $pos = $i % $length;
        $r = ord($str[$i]) ^ ord($key[$pos]);
        $str[$i] = chr($r);
    }
    return $str;
}

Example usage:

echo _tutorialspots_3('your password', 'your private key');

result:

      D

It isn’t a nice result, we need to convert to a nice result:

  • base64_encode
echo base64_encode( _tutorialspots_3('your password', 'your private key') );

Result:

AAAAAAAAExoFFhsXRA==

  • unpack
$unpack = unpack('H*',_tutorialspots_3('your password', 'your private key'));
echo $unpack[1];

Result:

000000000000131a05161b1744

To decrypt, we use this code:

echo _tutorialspots_3(_tutorialspots_3('your password','your private key'),'your private key');

We get the result:

your password

If we encrypt the encrypting string with base64_encode function, we use this code:

echo _tutorialspots_3(base64_decode('AAAAAAAAExoFFhsXRA=='),'your private key');

If we encrypt the encrypting string with unpack function, we use this code:

echo _tutorialspots_3(pack('H*','000000000000131a05161b1744'),'your private key');

Continuing…

Leave a Reply