接收错误警告:mcrypt_decrypt():IV参数必须与块大小一样长



我收到这个错误:

Warning: mcrypt_decrypt(): The IV parameter must be as long as the blocksize

它来自于用与php手册网站上的代码基本相同的代码加密变量(http://php.net/manual/en/function.mcrypt-encrypt.php)。当它全部放在一起时,它就可以工作了(我将它一分为二,用作include()文件,并添加了方便的输入和输出变量)。它对一个值进行加密,将其发布在$_GET变量上,然后在下一页加载时对其进行解密。然而,在解密时,我得到了错误。我猜这可能与将加密信息保存在$_GET变量上,然后读取它有关。例如,URL中的加密文本和$_GET标识符如下所示:Last_Song_ID=mIyFkMdMgVgSZU18wD/vJ3bI8qf++ea1/NtGrsajKd4=

在该文件中(错误发生在底部附近的$ciphertext_dec, MCRYPT_MODE_CBC, $iv_dec);

include('key.php');
$ciphertext_base64 = $de_in;
$ciphertext_dec = base64_decode($ciphertext_base64);
$iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
echo $iv_size . "<br>";
# retrieves the IV, iv_size should be created using mcrypt_get_iv_size()
$iv_dec = substr($ciphertext_dec, 0, $iv_size);
# retrieves the cipher text (everything except the $iv_size in the front)
$ciphertext_dec = substr($ciphertext_dec, $iv_size);
# may remove 00h valued characters from end of plain text
$plaintext_utf8_dec = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $key,
                                     $ciphertext_dec, MCRYPT_MODE_CBC, $iv_dec);
$de_out = $plaintext_utf8_dec;

加密文本来自主文件中的$_GET变量,该变量来自以下内容:

<?php
    # --- ENCRYPTION ---
    # the key should be random binary, use scrypt, bcrypt or PBKDF2 to
    # convert a string into a key
    # key is specified using hexadecimal
    include('key.php');
    # show key size use either 16, 24 or 32 byte keys for AES-128, 192
    # and 256 respectively
    $key_size =  strlen($key);
    //echo "Key size: " . $key_size . "n";
    if(!isset($en_in))
    $en_in = "No Input";
    # create a random IV to use with CBC encoding
    $iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
    echo $iv_size . "<br>";
    $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
    # use an explicit encoding for the plain text
    $plaintext_utf8 = utf8_encode($en_in);
    # creates a cipher text compatible with AES (Rijndael block size = 128)
    # to keep the text confidential 
    # only suitable for encoded input that never ends with value 00h
    # (because of default zero padding)
    $ciphertext = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key,
                                 $plaintext_utf8, MCRYPT_MODE_CBC, $iv);
    # prepend the IV for it to be available for decryption
    $ciphertext = $iv . $ciphertext;
    # encode the resulting cipher text so it can be represented by a string
    $ciphertext_base64 = base64_encode($ciphertext);
    $en_out = $ciphertext_base64;

?>

您不能通过GET参数传递base64,因为这些是有效的base64字符,可能与GET参数发生冲突:

EFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvxyz0123456789+/-

因此,您可能不会像预期的那样检索整个GET,而只是检索一部分。你可能想这样做来检查:

最后一行编码:

echo strlen($en_out);

在编码开始时:

echo strlen($de_in);

如果尺寸不匹配,那就是你的问题,因为上面提到和联系的原因,整个事情没有得到正确的通过。

编辑:关于解决方案,链接的问题中的第一个和第二个答案都很好。

最新更新