AES 128 CBC:如何计算正确的IV?

时间:2012-02-09 19:27:51

标签: php encryption openssl

<?php

$data = '
    -What is the answer to the Ultimate Question of Life, the Universe, and Everything ?
    -42
';
$method = 'AES-128-CBC';
$password = 'secret password';
$raw_output = $raw_input = true;

$iv_len = openssl_cipher_iv_length($method);
$iv = openssl_random_pseudo_bytes($iv_len);

$encrypted = openssl_encrypt($data, $method, $password, $raw_output, $iv);
var_dump($encrypted);


echo 'Decryption with known IV: OK';
$decrypted = openssl_decrypt($encrypted, $method, $password, $raw_input, $iv);
var_dump($decrypted);

echo 'Decryption with calculated IV: Fail<br><br>';
$iv = substr($encrypted, 0, $iv_len);
echo 'Without substring';
$decrypted = openssl_decrypt($encrypted, $method, $password, $raw_input, $iv);
var_dump($decrypted);
echo 'With substring';
$encrypted = substr($encrypted, $iv_len);
$decrypted = openssl_decrypt($encrypted, $method, $password, $raw_input, $iv);
var_dump($decrypted);

enter image description here

我做错了什么?

1 个答案:

答案 0 :(得分:3)

您似乎假设您的IV位于加密输出的开头,但您没有明确地将其放在那里。

尝试:

$encrypted = $iv . openssl_encrypt($data, $method, $password, $raw_output, $iv);

并尝试解密:

$iv = substr($encrypted, 0, $iv_len);
$encrypted = substr($encrypted, $iv_len);
$decrypted = openssl_decrypt($encrypted, $method, $password, $raw_input, $iv);
var_dump($decrypted);