0

How do I setup my IV in codeigniter 3 encryption library?

I have encryption code below which was running smoothly in Codeigniter 2 with PHP 5.6,

function encrypt($data, $secret) 
{ 
    //Generate a key from a hash 
    $key    = md5(utf8_encode($secret), true); 
    $data2  = utf8_encode($data); 
    $iv     = utf8_encode("jvz8bUAx"); 

    //Take first 8 bytes of $key and append them to the end of $key. 
    $key .= substr($key, 0, 8); 

    //Pad for PKCS7 
    $blockSize = mcrypt_get_block_size('tripledes', 'cbc'); 

    //Encrypt data 
    $encData = mcrypt_encrypt('tripledes', $key, $data2, MCRYPT_MODE_CBC, $iv); 

    return urlencode(base64_encode($encData)); 
} 

When I upgraded to CI 3 with PHP 7.1 mcrypt was deprecated already. So, I wanted to recreate the function in CI 3 using encryption library, but I cannot get the correct encrypted strings.

$this->load->library('encryption');

$key = md5(utf8_encode($secret), true); 
$key .= substr($key, 0, 8); 
$iv = utf8_encode("jvz8bUAx"); 

$amount = 1100;

$json = array(
    'Amount' => $amount
);

$data = json_encode($json);

$params = array(    
    'driver' => 'mcrypt',
    'cipher' => 'tripledes',
    'mode' => 'cbc',
    'key' => $key,
    'hmac' => false
);

$ciphertext = $this->encryption->encrypt($data, $params);
$ciphertext = urlencode(base64_encode($ciphertext));
3
  • please mention the error. Commented Dec 17, 2018 at 12:19
  • How do I setup IV Commented Dec 18, 2018 at 4:57
  • did you solve the problem? If so, could you accept the answer? Commented Jan 30, 2019 at 19:09

1 Answer 1

0

In the CI How it is works

Generate a random initialization vector (IV).

The library generates the IV for you and then prepends it for you to the resulting ciphertext. During the decryption, the IV is extracted from the ciphertext.

Since, by default, you cannot control the IV, the ciphertext will be different. If you want to really decrypt the old library encryption with the new one you have to prepend the IV as in the CI 3.

Sign up to request clarification or add additional context in comments.

2 Comments

Is there a way that I can prepend the IV in CI3?
If you look at the message length in the docs, the IV prepended to the cipher-text and the HMAC authentication message that is also prepended. The doc doesn't tell the separator, but, by looking the output, you can see the format. Rest is paring and concatenating.