codeigniter encryption and decryption code example

Example: encryption and decryption in codeigniter

Note* : You might require to load driver if no driver is loaded 
$this->encryption->initialize(
  array(
    'driver' => 'openssl',
    'cipher' => 'aes-256',
    'mode' => 'ctr'
  )
);

STEP 1: Load a encryption library
		
$this->load->library('encryption');

STEP 2: Create a encryption key for a config file application/config/config.php

$this->encryption->create_key(16);
############### OR #############
bin2hex($this->encryption->create_key(16)); // For more user friendly cipher text

Add this key inside the config file
$config['encryption_key'] = hex2bin(<your hex-encoded key>);

STEP 3: For encypt a plain text to cipher text

$plain_text = 'This is a plain-text message!';
$ciphertext = $this->encryption->encrypt($plain_text);

STEP 4: Decrypt Cipher text to plain text 

// Outputs: This is a plain-text message!
echo $this->encryption->decrypt($ciphertext);

Tags:

Php Example