2012-02-09 150 views
1
<?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 hereAES 128 CBC:如何计算正确的IV?

我在做什么错?

+0

如果我理解你的问题正确,你是假设加密字符串中的第16个字节是IV。有没有任何理由假设? IV是密钥的一部分,您无法从加密的字符串中计算出来。 – 2012-02-09 23:02:01

回答

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); 
相关问题