openssl_encrypt

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

openssl_encryptデータを暗号化する

説明

openssl_encrypt(
    string$data,
    string$cipher_algo,
    string$passphrase,
    int$options = 0,
    string$iv = "",
    string&$tag = null,
    string$aad = "",
    int$tag_length = 16
): string|false

与えられた文字列を与えられたメソッドとキーで暗号化して、 未加工の、または base64 エンコードされた文字列を返します。

パラメータ

data

暗号化するプレーンテキストメッセージ

cipher_algo

暗号メソッド。 使用可能なメソッドの一覧を取得するには、openssl_get_cipher_methods() を用います。

passphrase

パスフレーズ。 期待された長さより短かった場合は、 黙ってNUL 文字で埋められます。 期待された長さより長かった場合は、 黙って切り詰められます。

options

OPENSSL_RAW_DATAOPENSSL_ZERO_PADDING のビット OR。

iv

NULL ではない初期化ベクトル。

tag

AEAD 暗号モード (GCM または CCM) を使う場合の 認証タグをリファレンスで渡します。

aad

追加の認証済みデータ

tag_length

認証 tag の長さ。 GCMモードでは、この値は 4 から 16 の間です。

戻り値

成功した場合暗号化された文字列、失敗した場合に false を返します。

エラー / 例外

cipher_algo パラメータを通じて未知の暗号アルゴリズムが渡された場合、 E_WARNING レベルのエラーを発生します。

iv パラメータを通じて空値が渡された場合、 E_WARNING レベルのエラーを発生します。

変更履歴

バージョン説明
7.1.0tagaad および tag_length パラメータが追加されました。

例1 PHP 7.1以降で、AES を GCMモードで使う例

<?php
//$key should have been previously generated in a cryptographically safe way, like openssl_random_pseudo_bytes
$plaintext = "message to be encrypted";
$cipher = "aes-128-gcm";
if (
in_array($cipher, openssl_get_cipher_methods()))
{
$ivlen = openssl_cipher_iv_length($cipher);
$iv = openssl_random_pseudo_bytes($ivlen);
$ciphertext = openssl_encrypt($plaintext, $cipher, $key, $options=0, $iv, $tag);
//store $cipher, $iv, and $tag for decryption later
$original_plaintext = openssl_decrypt($ciphertext, $cipher, $key, $options=0, $iv, $tag);
echo
$original_plaintext."\n";
}
?>

例2 PHP 7.1 より前のバージョンで、AES を使う例

<?php
//$key previously generated safely, ie: openssl_random_pseudo_bytes
$plaintext = "message to be encrypted";
$ivlen = openssl_cipher_iv_length($cipher="AES-128-CBC");
$iv = openssl_random_pseudo_bytes($ivlen);
$ciphertext_raw = openssl_encrypt($plaintext, $cipher, $key, $options=OPENSSL_RAW_DATA, $iv);
$hmac = hash_hmac('sha256', $ciphertext_raw, $key, $as_binary=true);
$ciphertext = base64_encode( $iv.$hmac.$ciphertext_raw );

//decrypt later....
$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);
$original_plaintext = openssl_decrypt($ciphertext_raw, $cipher, $key, $options=OPENSSL_RAW_DATA, $iv);
$calcmac = hash_hmac('sha256', $ciphertext_raw, $key, $as_binary=true);
if (
hash_equals($hmac, $calcmac))// timing attack safe comparison
{
echo
$original_plaintext."\n";
}
?>

参考

To Top