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

发布于 2025-01-04 07:08:59 字数 1059 浏览 1 评论 0原文

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

在此处输入图像描述

我做错了什么?

<?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

What am I doing wrong?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

北渚 2025-01-11 07:08:59

看起来你假设你的 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);

It seems like you are assuming that your IV is at the beginning of the encrypted output but your are not explicitly putting it there.

Try:

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

and try decrypting with:

$iv = substr($encrypted, 0, $iv_len);
$encrypted = substr($encrypted, $iv_len);
$decrypted = openssl_decrypt($encrypted, $method, $password, $raw_input, $iv);
var_dump($decrypted);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文