Encryption Service

Important

DO NOT use this or any other encryption library forpassword storage! Passwords must be hashed instead, and youshould do that through PHP’s Password Hashing extension.

The Encryption Service provides two-way symmetric (secret key) data encryption.The service will instantiate and/or initialize anencryption handler to suit your parameters as explained below.

Encryption Service handlers must implement CodeIgniter’s simple EncrypterInterface.Using an appropriate PHP cryptographic extension or third-party library may requireadditional software is installed on your server and/or might need to be explicitlyenabled in your instance of PHP.

The following PHP extensions are currently supported:

This is not a full cryptographic solution. If you need more capabilities, for example,public-key encryption, we suggest you consider direct use of OpenSSL orone of the other Cryptography Extensions.A more comprehensive package like Halite(an O-O package built on libsodium) is another possibility.

Note

Support for the MCrypt extension has been dropped, as that hasbeen deprecated as of PHP 7.2.

Using the Encryption Library

Like all services in CodeIgniter, it can be loaded via Config\Services:

  1. $encrypter = \Config\Services::encrypter();

Assuming you have set your starting key (see Configuring the Library),encrypting and decrypting data is simple - pass the appropriate string to encrypt()and/or decrypt() methods:

  1. $plainText = 'This is a plain-text message!';
  2. $ciphertext = $encrypter->encrypt($plainText);
  3.  
  4. // Outputs: This is a plain-text message!
  5. echo $encrypter->decrypt($ciphertext);

And that’s it! The Encryption library will do everything necessaryfor the whole process to be cryptographically secure out-of-the-box.You don’t need to worry about it.

Configuring the Library

The example above uses the configuration settings found in app/Config/Encryption.php.

There are only two settings:

OptionPossible values (default in parentheses)
keyEncryption key starter
driverPreferred handler (OpenSSL)

You can replace the config file’s settings by passing a configurationobject of your own to the Services call. The $config variable must bean instance of either the Config\Encryption class or an objectthat extends CodeIgniter\Config\BaseConfig.

  1. $config = new Config\Encryption();
  2. $config->key = 'aBigsecret_ofAtleast32Characters';
  3. $config->driver = 'OpenSSL';
  4.  
  5. $encrypter = \Config\Services::encrypter($config);

Default Behavior

By default, the Encryption Library uses the OpenSSL handler. That handler encrypts usingthe AES-256-CTR algorithm, your configured key, and SHA512 HMAC authentication.

Setting Your Encryption Key

Your encryption key must be as long as the encryption algorithm in use allows.For AES-256, that’s 256 bits or 32 bytes (characters) long.

The key should be as random as possible, and it must not be a regular text string,nor the output of a hashing function, etc. To create a proper key,you can use the Encryption library’s createKey() method.

  1. // $key will be assigned a 32-byte (256-bit) random key
  2. $key = Encryption::createKey(32);

The key can be stored in app/Config/Encryption.php, or you can designa storage mechanism of your own and pass the key dynamically when encrypting/decrypting.

To save your key to your app/Config/Encryption.php, open the fileand set:

  1. public $key = 'YOUR KEY';

Encoding Keys or Results

You’ll notice that the createKey() method outputs binary data, whichis hard to deal with (i.e. a copy-paste may damage it), so you may usebin2hex(), hex2bin() or Base64-encoding to work with the key ina more friendly manner. For example:

  1. // Get a hex-encoded representation of the key:
  2. $encoded = bin2hex(Encryption::createKey(32));
  3.  
  4. // Put the same value in your config with hex2bin(),
  5. // so that it is still passed as binary to the library:
  6. $key = hex2bin(<your hex-encoded key>);

You might find the same technique useful for the resultsof encryption:

  1. // Encrypt some text & make the results text
  2. $encoded = base64_encode($encrypter->encrypt($plaintext));

Encryption Handler Notes

OpenSSL Notes

The OpenSSL extension has been a standard part of PHP for a long time.

CodeIgniter’s OpenSSL handler uses the AES-256-CTR cipher.

The key your configuration provides is used to derive two other keys, one forencryption and one for authentication. This is achieved by way of a technique knownas an HMAC-based Key Derivation Function (HKDF).

Message Length

An encrypted string is usually longer than the original, plain-text string (depending on the cipher).

This is influenced by the cipher algorithm itself, the initialization vector (IV)prepended to the cipher-text, and the HMAC authentication message that is also prepended.Furthermore, the encrypted message is also Base64-encoded so that it is safefor storage and transmission regardless of the character-set in use.

Keep this information in mind when selecting your data storage mechanism.Cookies, for example, can only hold 4K of information.

Using the Encryption Service Directly

Instead of (or in addition to) using Services as described in Using the Encryption Library,you can create an “Encrypter” directly, or change the settings of an existing instance.

  1. // create an Encrypter instance
  2. $encryption = new \Encryption\Encryption();
  3.  
  4. // reconfigure an instance with different settings
  5. $encrypter = $encryption->initialize($config);

Remember, that $config must me an instance of either a ConfigEncryption classor an object that extends CodeIgniterConfigBaseConfig.

Class Reference

  • CodeIgniter\Encryption\Encryption
    • static createKey($length)

Parameters:

  1. - **$length** (_int_) Output lengthReturns:

A pseudo-random cryptographic key with the specified length, or FALSE on failureReturn type:string

Creates a cryptographic key by fetching random data fromthe operating system’s sources (i.e. /dev/urandom).

  • initialize($config)

Parameters:

  1. - **$config** (_BaseConfig_) Configuration parametersReturns:

CodeIgniter\Encryption\EncrypterInterface instanceReturn type:CodeIgniter\Encryption\EncrypterInterfaceThrows:CodeIgniter\Encryption\EncryptionException

Initializes (configures) the library to use different settings.

Example:

  1. $encrypter = $encryption->initialize(['cipher' => '3des']);

Please refer to the Configuring the Library section for detailed info.

  • CodeIgniter\Encryption\EncrypterInterface
    • encrypt($data, $params = null)

Parameters:

  1. - **$data** (_string_) Data to encrypt
  2. - **$params** Configuration parameters (key)Returns:

Encrypted data or FALSE on failureReturn type:stringThrows:CodeIgniter\Encryption\EncryptionException

Encrypts the input data and returns its ciphertext.

If you pass parameters as the second argument, the key elementwill be used as the starting key for this operation if $paramsis an array; or the starting key may be passed as a string.

Examples:

  1. $ciphertext = $encrypter->encrypt('My secret message');
  2. $ciphertext = $encrypter->encrypt('My secret message', ['key' => 'New secret key']);
  3. $ciphertext = $encrypter->encrypt('My secret message', 'New secret key');
  • decrypt($data, $params = null)

Parameters:

  1. - **$data** (_string_) Data to decrypt
  2. - **$params** Configuration parameters (key)Returns:

Decrypted data or FALSE on failureReturn type:stringThrows:CodeIgniter\Encryption\EncryptionException

Decrypts the input data and returns it in plain-text.

If you pass parameters as the second argument, the key elementwill be used as the starting key for this operation if $paramsis an array; or the starting key may be passed as a string.

Examples:

  1. echo $encrypter->decrypt($ciphertext);
  2. echo $encrypter->decrypt($ciphertext, ['key' => 'New secret key']);
  3. echo $encrypter->decrypt($ciphertext, 'New secret key');