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

Strange bytes is added to the end of string when using cookie encryption

// bootstrap.php
    $di->setShared('crypt', function()
    {
        $crypt = new \Phalcon\Crypt;
        $crypt->setKey('asasasasasasasas'); // 16 bytes, it's no matter what symbols are used
        return $crypt;
    });
    $di->setShared('cookies', function ()
    {
        $cookies = new \Phalcon\Http\Response\Cookies();
        $cookies->useEncryption(true); // if false, bug is not reproduces
        return $cookies;
    });
class LoginController extends \Phalcon\Mvc\Controller
{
    public function indexAction() 
    {
        $token = $this->security->getSaltBytes(50);
        $this->cookies->set('token', $token, time() + 31536000);
        $result = base64_encode($token); // bTRscnRXTmlGUU1aZ3h6OEVyWGh5UQ==
    ...
class ProfileController extends \Phalcon\Mvc\Controller
{
    public function indexAction() 
    {
        $token = $this->cookies->get('token')->getValue();
        $result = base64_encode($token); // bTRscnRXTmlGUU1aZ3h6OEVyWGh5UQAAAAAAAAAAAAA=
    ...

There are two separate pages, login and profile. Why extra bytes are added in decoded token?

edited Sep '15

This is not a bug, that's caused because of padding, you can change the padding this way:

$di->setShared('crypt', function()
{
        $crypt = new \Phalcon\Crypt;
        $crypt->setMode(MCRYPT_MODE_CFB);
        $crypt->setKey('asasasasasasasas'); // 16 bytes, it's no matter what symbols are used
        return $crypt;
});
edited Aug '15

Phalcon throws exception "Parameter 'scheme' must be a long/integer". I see in PHPStorm that in the internal representation of mcrypt this constant have string value:

   define ('MCRYPT_MODE_CFB', "cfb");

The same is described in comment here https://php.net/manual/ru/mcrypt.constants.php



34.6k
Accepted
answer

I've fixed the example

edited Sep '15

Thank you! I think that it would be useful for beginners to see it here https://docs.phalcon.io/en/latest/reference/cookies.html because default behavior, described in docs

use Phalcon\Crypt;

$di->set('crypt', function () {
    $crypt = new Crypt();
    $crypt->setKey('#1dj8$=dp?.ak//j1V$'); // Use your own key!
    return $crypt;
});

leads to confusing results.