Image

ナレッジベース → テキストを暗号化および復号化するための PHP スクリプトの例

[スクリプト]
公開日: 10.10.2023

以下は、opensslを使用してテキスト文字列を暗号化および復号化するための、php 8.1でテストされたスクリプトの例です。

nano encrypt-decrypt.php
<?php 

define('ENCRYPTION_KEY', '<mark>my-secret-key-there-2121</mark>');

// 暗号化
$plaintext = "<output>PHP 8.1での暗号化テスト文字列</output>";
$ivlen = openssl_cipher_iv_length($cipher="AES-128-CBC");
$iv = openssl_random_pseudo_bytes($ivlen);
$ciphertext_raw = openssl_encrypt($plaintext, $cipher, ENCRYPTION_KEY, $options=OPENSSL_RAW_DATA, $iv);
$hmac = hash_hmac('sha256', $ciphertext_raw, ENCRYPTION_KEY, $as_binary=true);
$ciphertext = base64_encode( $iv.$hmac.$ciphertext_raw );
<output>echo $ciphertext.'<br>';</output>
 
// 復号化
$c = base64_decode($ciphertext);
$ivlen = openssl_cipher_iv_length($cipher="AES-128-CBC");
$iv = substr($c, 0, $ivlen);
$hmac = substr($c, $ivlen, $sha2len=32);
$ciphertext_raw = substr($c, $ivlen+$sha2len);
$plaintext = openssl_decrypt($ciphertext_raw, $cipher, ENCRYPTION_KEY, $options=OPENSSL_RAW_DATA, $iv);
$calcmac = hash_hmac('sha256', $ciphertext_raw, ENCRYPTION_KEY, $as_binary=true);
if (hash_equals($hmac, $calcmac))
{
    <output>echo $plaintext;</output>
}

?>

最初の行は暗号化の結果で、次の行は復号化の結果です。同じフレーズを変更せずにページを更新すると、常に異なる暗号化結果が得られますが、復号化結果は常に同じです。

これらの関数を別々のファイルに分ける場合、ENCRYPTION_KEYのパラメーターを別ファイルに移動する必要があります。





No Comments Yet