Search code examples
phpcodeignitercodeigniter-2mcrypt

mcrypt_decrypt with tripledes and cbc not working proper


enter image description here

As per above screenshot my decode data will see like this when i can view source in browser. otherwise decrypt proper but not store in session proper due to this problem.Thanks in Advance.

  function decrypt($data, $key) {        
    $iv = chr(0) . chr(0) . chr(0) . chr(0) . chr(0) . chr(0) . chr(0) . chr(0); //8 bytes array filled with zeros        

    $key = mb_convert_encoding($key, 'UTF-16LE'); 
    $key = md5($key, true); 
    $key = $key . $key;
    $tripleKey = substr($key, 0, mcrypt_get_key_size(CIPHER, MODE));

    $decodedText = mcrypt_decrypt(CIPHER, $tripleKey, base64_decode($data), MODE, $iv);

    // check and remove PKCS#7 padding
    if (!$decodedText) {
        return $decodedText;
    }
    $lastByte = ord($decodedText[strlen($decodedText) - 1]);
    if ($lastByte == 0 || $lastByte > mcrypt_get_block_size(CIPHER, MODE)) {
        return FALSE;
    }
    $paddingText = substr($decodedText, -$lastByte, $lastByte);
    $decodedText = substr($decodedText, 0, -$lastByte);
    if ($paddingText != str_repeat(chr($lastByte), $lastByte)) {
        return FALSE;
    }

    return $decodedText;
}

Solution

  • Please try updating line as per below.

    $decodedText = str_replace("\0", "", $decodedText);
    return $decodedText;