Codeigniter 3 Mcrypt库加密不起作用

时间:2018-12-17 12:06:23

标签: php encryption codeigniter-3 mcrypt

如何在Codeigniter 3加密库中设置IV?

我下面有加密代码,该代码在PHP 5.6的Codeigniter 2中运行顺利,

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)); 
} 

当我使用PHP 7.1升级到CI 3时,已经不建议使用mcrypt。因此,我想使用加密library在CI 3中重新创建该函数,但是我无法获得正确的加密字符串。

$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));

1 个答案:

答案 0 :(得分:0)

CI How it is works

  

生成随机初始化向量(IV)。

该库为您生成IV,然后将其添加到生成的密文中。在解密期间,从密文中提取IV。

由于默认情况下无法控制IV,因此密文将有所不同。如果您想用新的库真正解密旧的库加密,则必须像CI 3一样在IV之前加上前缀。