2012-02-09 4 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はキーの一部です。暗号化された文字列からIVを計算することはできません。 –

答えて

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); 
関連する問題