2012-02-09 139 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); 
相關問題