openssl_encrypt
(PHP 5 >= 5.3.0, PHP 7, PHP 8)
openssl_encrypt — 加密數據
說明
openssl_encrypt(
string
string
string
int
string
string
string
int
): string|false
string
$data,string
$cipher_algo,string
$passphrase,int
$options = 0,string
$iv = "",string
&$tag = null,string
$aad = "",int
$tag_length = 16): string|false
以指定的方式和 key 加密數據,返回原始或 base64 編碼后的字串。
參數
-
data -
待加密的明文資訊數據。
-
cipher_algo -
密碼學方式。openssl_get_cipher_methods() 可獲取有效密碼方式列表。
-
passphrase -
口令(passphrase)。 若 passphrase 比預期長度短,將靜默用
NUL填充; 若比預期長度更長,將靜默截斷。 -
options -
options是以下標記的按位或:OPENSSL_RAW_DATA、OPENSSL_ZERO_PADDING。 -
iv -
非 NULL 的初始化向量。
-
tag -
使用 AEAD 密碼模式(GCM 或 CCM)時傳引用的驗證標籤。
-
aad -
附加的驗證數據。
-
tag_length -
驗證
tag的長度。GCM 模式時,它的範圍是 4 到 16。
返回值
成功時返回加密後的字串, 或者在失敗時返回 false。
錯誤/異常
cipher_algo 傳入未知演算法時,產生 E_WARNING 級別的錯誤。
iv 傳入空字串時產生 E_WARNING 級別的錯誤。
更新日誌
| 版本 | 說明 |
|---|---|
| 7.1.0 | 增加了 tag、aad、tag_length 參數 |
範例
示例 #1 PHP 7.1+ 下 GCM 模式的 AES 認證加密例子
<?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";
}
?>