Views: 158
Last Modified: 18.10.2022

  Encrypted cookies

Encrypted cookies Cookie - is a text string of information, sent to a browser by a site visitor and which is saved in file on the site visitor device. Usually, a cookie is used to determine a user unique status, last visit time, personal settings, shopping cart unique ID and etc.
(\Bitrix\Main\Web\CryptoCookie) allows sending data to user, without disclosing contents and without allowing to modify data inside. Available from main 20.5.400.

Configuration

For the kernel to be capable to encrypt the data, indicate crypto_key in the settings /bitrix/.settings.php . By default, it's generated automatically in new distribution packages.

If it's unavailable, add it manually to kernel settings file:

<?php
return [
    //...
    'crypto' => [
        'value' => [
            'crypto_key' => 'mysupersecretphrase',
            //we recommend to set 32-character string from a-z0-9,
        ],
        'readonly' => true,
    ]

    //...
];

  Examples

Setting a Cookie

To set an encrypted cookie, just create an object as in the snippet below, into a desired Response:

$cookie = new \Bitrix\Main\Web\CryptoCookie('someName', 'secret value');
\Bitrix\Main\Context::getCurrent()->getResponse()->addCookie($cookie);

Because the cookie is limited in length and data is encrypted and packaged in base64, to avoid data loss, the kernel can create several cookies with encrypted value.

As the result, http response will contain cookie someName with the value -crpt-someName_0. And cookie someName_0 with already encrypted value such as DRMg6jrwXO1aUxTvdyBYyT-3_bCqomI9MMN_enurA5abplMm2OiSlNdu_1zgjbkKT_3D3uT8366.

Reading a Cookie

To get access to encrypted cookies value, it's sufficient to use standard kernel API for cookie handling

$httpRequest = \Bitrix\Main\Context::getCurrent()->getRequest();

echo $httpRequest->getCookie('someName');
//secret value

Kernel automatically determines that cookie is encrypted or not encrypted, unpackages the value and decrypts it. In case the value cannot be decrypted, gets an empty value.




Courses developed by Bitrix24