We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

Problem with Crypt base64

Hi, I have a simple problem, with Crypt class, loot ak following code:

$cryptPhalcon = new Phalcon\Crypt();
$text = 'how are you';
var_dump($text);

echo '<br> ------------------------- ENCRYPT PHALCON--------------------- <br>';
$encrypt = $cryptPhalcon->encryptBase64($text);
var_dump($encrypt);

echo '<br> ------------------------- DECRYPT PHALCON--------------------- <br>';
$decrypt = $cryptPhalcon->decryptBase64($encrypt);
var_dump($decrypt);

var_dump($decrypt == $text);

and output is:

string 'how are you' (length=11)

------------------------- ENCRYPT PHALCON--------------------- 
string 'm5fRk+73DaFc5mXTSm4E8aIVj0PL4jCPrmCPILKV0rveuLGVgx5ZqrRUktHp5t2baAyzchhTzqnOgQTQ98sZ1g==' (length=88)

------------------------- DECRYPT PHALCON--------------------- 
string 'how are you���������������������' (length=32)
boolean false

Can someone help me? I hoped it would return true, but maybe i am mistaken...

Can you just use PHPs base64 encode or decode? I don't the reasoning for trying to use phalcons.

And actually this interested me enough to look it up in the source, and it appears that phalcon's base64 encode/decode is actually just a wrapper for PHP's

https://github.com/phalcon/cphalcon/blob/bf9da26e6e20ea05dd69881b9cd0c2536ec53bcb/ext/kernel/string.c#L985

Am I off base here Andres?



11.2k
Accepted
answer
edited Nov '14

The crypt makes padding for reasons.

The easiest way to work is to do something like this

        $cryptPhalcon = new \Phalcon\Crypt();

        $text = 'Phalcon Crypto';
        $key = 'The cake is a lie!';

        $encrypt = $cryptPhalcon->encryptBase64($text, $key);
        $decrypt = trim($cryptPhalcon->decryptBase64($encrypt, $key));

        var_dump($text);
        echo '<br> ------------------------- ENCRYPT PHALCON--------------------- <br>';
        var_dump($encrypt);
        echo '<br> ------------------------- DECRYPT PHALCON--------------------- <br>';
        var_dump($decrypt);
        echo '<br>';

        var_dump($decrypt == $text);

        die();

The output would be something like this

    string(14) "Phalcon Crypto"
    ------------------------- ENCRYPT PHALCON---------------------
    string(88) "o24rGA2ZVISdZ+pMk2ljUXiwyqGVjG3LH+rkhW/LGosofQm7GkWo5ppPDAwUndO0ngTT0ZpxUNxP8CrkM1olyw=="
    ------------------------- DECRYPT PHALCON---------------------
    string(14) "Phalcon Crypto"
    bool(true) 


98.9k

The extra characters are there because of padding. Block cipher modes for symmetric-key encryption algorithms in ECB/CBC modes require plain text input that is a multiple of the block size, so messages must be padded to bring them to this length when they're decripted. This is why you find extra zero null characters at the end of the input causing both strings not to be the same.