Back to menu (Japanese) (English)
AES-256-CBC Authenticated Encryption example for PHP 5.6+ (ivlen:16 sha512)
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);
}
...
?>