PHP警告:openssl_decrypt():传递的IV长32个字节,比所选密码预期的16个字节长

时间:2018-08-06 20:46:13

标签: php openssl php-5.6 php-openssl php-7.2

我需要在我的应用程序中实现openSSL,因为我们必须将版本从5.6更改为7.2。

我想了解如何解决此问题。

关于我的环境或我如何使用该应用程序的任何疑问,只要问我会做出答复即可。

<?php

$dados = '#########################################################';

$key = '################################';
$iv = '################################';

/**
 * running in version 7.2
 */
$data = openssl_decrypt($dados, 'AES-128-CBC', $key, OPENSSL_RAW_DATA | OPENSSL_ZERO_PADDING, $iv);
/**
 * Erro:
 * $ clear && ./php descriptografa-senha.php
 *
 * PHP Warning:  openssl_decrypt(): IV passed is 32 bytes long which is longer than the 16 expected by selected cipher, truncating in ./descriptografa-senha.php on line 12
 * PHP Stack trace:
 * PHP   1. {main}() ./descriptografa-senha.php:0
 * PHP   2. openssl_decrypt() ./descriptografa-senha.php:12
 *
 * Warning: openssl_decrypt(): IV passed is 32 bytes long which is longer than the 16 expected by selected cipher, truncating in ./descriptografa-senha.php on line 12
 *
 * Call Stack:
 *     0.4121     125736   1. {main}() ./descriptografa-senha.php:0
 *     0.4121     126312   2. openssl_decrypt() ./descriptografa-senha.php:12
 */

/**
 * running in version 5.6
 */
$mcrypt_cipher = MCRYPT_RIJNDAEL_256;
$mcrypt_mode = MCRYPT_MODE_CBC;
$encrypted = $dados;

$iv_utf = mb_convert_encoding($iv, 'UTF-8');
$decrypted = mcrypt_decrypt($mcrypt_cipher, $key, base64_decode($encrypted), $mcrypt_mode, $iv_utf);

print_r($decrypted);
/**
 * performed normally
 */

这是生成加密的代码,看看您是否可以理解并帮助我解决问题,用于加密的语言是C#,用于解密和PHP 7.2的语言

public static string Cryptography(string text, string pass = "#############################")
{
    if (string.IsNullOrEmpty(pass))
        return string.Empty;

    var rijndaelmanaged = new RijndaelManaged();
    rijndaelmanaged.KeySize = 256;
    rijndaelmanaged.BlockSize = 256;
    rijndaelmanaged.Padding = PaddingMode.PKCS7;
    rijndaelmanaged.Key = Convert.FromBase64String(Base64Encode(pass));

    rijndaelmanaged.IV = Convert.FromBase64String(Base64Encode(vetorInicializacao));

    var encrypt = rijndaelmanaged.CreateEncryptor(rijndaelmanaged.Key, rijndaelmanaged.IV);
    byte[] xBuff = null;
    using (var ms = new MemoryStream())
    {
        using (var cs = new CryptoStream(ms, encrypt, CryptoStreamMode.Write))
        {
            byte[] xXml = Encoding.UTF8.GetBytes(text);
            cs.Write(xXml, 0, xXml.Length);
        }

        xBuff = ms.ToArray();
    }

    String out = Convert.ToBase64String(xBuff);
    return out;
}

2 个答案:

答案 0 :(得分:0)

从手册:

  

$ iv与$ password一样,是一个字节字符串。

您似乎已将$iv编码为十六进制字符串:

$iv = '################################';

您可能只需要将其转换为二进制字节字符串:

$iv = hex2bin('################################');

同上$key

答案 1 :(得分:0)

解决方案是使用phpseclib/mcrypt_compat

composer require phpseclib/mcrypt_compat