openssl_encrypt
(PHP 5 >= 5.3.0, PHP 7)
openssl_encrypt — データを暗号化する
説明
openssl_encrypt
( string $data
, string $method
, string $key
[, int $options
= 0
[, string $iv
= ""
[, string &$tag
= NULL
[, string $aad
= ""
[, int $tag_length
= 16
]]]]] ) : string|false
与えられた文字列を与えられたメソッドとキーで暗号化して、 未加工の、または base64 エンコードされた文字列を返します。
パラメータ
data
- 暗号化するプレーンテキストメッセージ
method
- 暗号メソッド。 使用可能なメソッドの一覧を取得するには、openssl_get_cipher_methods() を用います。
key
- キー
options
OPENSSL_RAW_DATA
とOPENSSL_ZERO_PADDING
のビット OR。iv
- NULL ではない初期化ベクトル。
tag
- AEAD 暗号モード (GCM または LCM) を使う場合の 認証タグを参照で渡します。
aad
- 追加の認証データ
tag_length
- 認証
tag
の長さ。 GCMモードでは、この値は 4 から 16 の間です。
返り値
成功した場合暗号化された文字列、失敗した場合に false
を返します。
エラー / 例外
method
パラメータを通じて未知の暗号アルゴリズムが渡された場合、
E_WARNING
レベルのエラーを発生します。
iv
パラメータを通じて空値が渡された場合、
E_WARNING
レベルのエラーを発生します。
変更履歴
バージョン | 説明 |
---|---|
7.1.0 | tag 、aad および
|
例
例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 5.6以降で、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))//PHP 5.6+ timing attack safe comparison{ echo $original_plaintext."\n";}?>