メニューに戻る  日本語版(Japanese)   英語版(English)

PHP用 AES-256-CBC 例

PHP5.6+用 AES-256-CBC 認証付き暗号例 (ivlen:16 sha512)

PHP 説明書

平文
鍵文字列
擬似乱数 sample
CV3bxgiaHMkjwIgkC7hdr3eq28vTlD0q
暗号文
復号文

Sample code to hide configuration.

The file "ht_config.dat" is hidden from WEB browser by Apache and won't be committed to GitHub.

% cat .ht_config.dat

<?php
define("HIDDEN_KEY", "jFzMTei3Ha8fu0ioGPc8Qzg2OCdpXyWt");
?>

Sample code to decrypt an access code of another WEB service

<?php
...
require_once ".ht_config.dat";
function my_decrypt($key, $cipher_text)
{
    $c = base64_decode($cipher_text);
    $ivlen = openssl_cipher_iv_length("aes-256-cbc");
    $iv = substr($c, 0, $ivlen);
    $hmac = substr($c, $ivlen, 512/8);
    $ciphertext_raw = substr($c, $ivlen + (512/8));
    $original_plaintext = openssl_decrypt($ciphertext_raw, "aes-256-cbc", $key, OPENSSL_RAW_DATA, $iv);
    $calcmac = hash_hmac('sha512', $ciphertext_raw, $key, $as_binary = true);
    if (hash_equals(bin2hex($hmac), bin2hex($calcmac)))//PHP 5.6+ timing attack safe comparison
    {
        return $original_plaintext;
    }
    return false;
}
define("ENCRYPTED_ACCESS_CODE", "l59DIPIWOx1s6OOTKB7BonvDIUXGvHiHEmlyDamC8tNqlUM+QRFL+xbdLlodETt0Hr/QscCre6ZZTR5WhzCJV1PpGneh8yz8llmV/8DaErlbMHzVR7ToT0biWI5a1YtTAvt38URjhypdceRomyOrAE1PJtYMvaDk4DOXXTUMoMf8er1r6LFZ7H+SESJIZSLD");
$original_access_code = my_decrypt(HIDDEN_KEY, ENCRYPTED_ACCESS_CODE);
if ($original_access_code !== false)
{
    access_another_WEB_service($original_access_code);
}
...
?>

株式会社好試力研究所