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


There are some methods to encrypt your data with a private key.

Method 1:

function _tutorialspots_1($str, $key = '')
{
    if ($key == '')
        return $str;
    $key = str_replace(chr(32), '', $key);
    if (strlen($key) < 8)
        exit('error');
    $kl = strlen($key) < 32 ? strlen($key) : 32;
    $k = array();
    for ($i = 0; $i < $kl; $i++) {
        $k[$i] = ord($key{$i}) & 0x1F;
    }
    $j = 0;
    for ($i = 0; $i < strlen($str); $i++) {
        $e = ord($str{$i});
        $str{$i} = $e & 0xE0 ? chr($e ^ $k[$j]) : chr($e);
        $j++;
        $j = $j == $kl ? 0 : $j;
    }
    return $str;
}

Note: your private key must have string length greater than 8.

Example usage:

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

result:

““0bhercjya

In the resulting string has special characters. We will convert the resulting string into a nice result:

echo base64_encode('````0bhercjya');

Result:

YGBgYDBiaGVyY2p5YQ==

$unpack = unpack('H*','````0bhercjya');
echo $unpack[1];

Result:

606060603062686572636a7961

To decrypt, we use this code:

echo _tutorialspots_1('````0bhercjya','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_1(base64_decode('YGBgYDBiaGVyY2p5YQ=='),'your private key');

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

echo _tutorialspots_1(pack('H*','606060603062686572636a7961'),'your private key');

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

Leave a Reply