php 暗号化、複合化(openssl_encrypt(),openssl_decrypt(),mcrypt_xxx())

作成日:2020-10-08, 更新日:2022-09-22

基本

・mcryptとopensslのどちらでもいける
・mcryptはPHP7.2より非推奨

opensslを使って暗号化、複合化

$key = 〇〇〇〇〇〇;
$org_str = '暗号化したい文字列';

// 暗号化
$enc_str = openssl_encrypt($org_str, 'AES-128-ECB', $key);

// 複合化
$dec_str = openssl_decrypt($enc_str, 'AES-128-ECB', $key);

echo $enc_str;
echo $dec_str;

mcryptを使って暗号化、複合化

$key = 〇〇〇〇〇〇;
$org_str = '暗号化したい文字列';

/* モジュールをオープンし、IV を作成 */ 
$td      = mcrypt_module_open('des', '', 'ecb', '');
$key     = substr($key, 0, mcrypt_enc_get_key_size($td));
$iv_size = mcrypt_enc_get_iv_size($td);
$iv      = mcrypt_create_iv($iv_size, MCRYPT_RAND);

/* 暗号化ハンドルを初期化 */
if (mcrypt_generic_init($td, $key, $iv) != -1) {

	/* 暗号化 */
	$enc_str = mcrypt_generic($td, $org_str);
	mcrypt_generic_deinit($td);

	/* 復号のため、バッファを再度初期化 */
	mcrypt_generic_init($td, $key, $iv);
	$dec_str = mdecrypt_generic($td, $enc_str);

	/* 後始末 */
	mcrypt_generic_deinit($td);
	mcrypt_module_close($td);

	echo $enc_str;
	echo $dec_str;
}

undefined function mcrypt_module_open()

▼「mcrypt_module_open()」を実行すると下記のようなエラーが出るかも。

Fatal error:  Uncaught Error: Call to undefined function mcrypt_module_open() in ~

対策

▼php.iniを確認し、extensionの指定がコメントアウトされていたらコメントを外す

;extension=php_mcrypt.dll
extension=php_mcrypt.dll

関連項目