【问题标题】:Codeigniter 3 Mcrypt library encryption not workingCodeigniter 3 Mcrypt库加密不起作用
【发布时间】:2019-05-17 19:13:18
【问题描述】:

如何在 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 已被弃用。因此,我想在 CI 3 中使用加密 library 重新创建该函数,但我无法获得正确的加密字符串。

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

【问题讨论】:

  • 请指出错误。
  • 如何设置 IV
  • 问题解决了吗?如果是这样,你能接受答案吗?

标签: php encryption codeigniter-3 mcrypt


【解决方案1】:

CI How it is works

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

该库为您生成 IV,然后为您将其添加到生成的密文中。在解密过程中,IV是从密文中提取出来的。

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

【讨论】:

  • 有没有办法可以在 CI3 中添加 IV?
  • 如果您查看文档中的message lengththe IV prepended to the cipher-text and the HMAC authentication message that is also prepended. 文档不会告诉分隔符,但是通过查看输出,您可以看到格式。休息是配对和连接。
猜你喜欢
  • 2013-01-20
  • 1970-01-01
  • 2016-10-01
  • 2017-11-10
  • 2016-06-18
  • 2016-04-22
  • 2013-12-28
  • 2018-05-30
  • 2011-11-13
相关资源
最近更新 更多