<?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);
我做错了什么?
答案 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);