openssl_encrypt加密数据
string openssl_encrypt ( string $data , string $method , string $key [, int $options = 0 [, string $iv = "" [, string &$tag = NULL [, string $aad = "" [, int $tag_length = 16 ]]]]] )
参数
data 待加密的明文信息数据。
method 密码学方式。openssl_get_cipher_methods() 可获取有效密码方式列表。
key 密钥
options options 是以下标记的按位或: OPENSSL_RAW_DATA 、 OPENSSL_ZERO_PADDING。
iv 非 NULL 的初始化向量。
tag 使用 AEAD 密码模式(GCM 或 CCM)时传引用的验证标签。
aad 附加的验证数据。
tag_length 验证 tag 的长度。GCM 模式时,它的范围是 4 到 16。
#返回值
成功时返回加密后的字符串, 或者在失败时返回 FALSE。
#错误/异常
method 传入未知算法时,产生 E_WARNING 级别的错误。
iv 传入空字符串时产生 E_WARNING 级别的错误。
openssl_decrypt解密数据
string openssl_decrypt ( string $data , string $method , string $key [, int $options = 0 [, string $iv = "" [, string $tag = "" [, string $aad = "" ]]]] )
#参数
data 将被解密的密文。
method 加密算法,使用openssl_get_cipher_methods()函数获取可用的加密算法列表。
key 密钥。
options options can be one of OPENSSL_RAW_DATA, OPENSSL_ZERO_PADDING.
iv 非空的初始化向量。
tag AEAD密码模式中的身份验证标签。 如果是错误的,验证失败,函数返回FALSE.
aad 额外的认证数据。
#返回值
The decrypted string on success 或者在失败时返回 FALSE.
#错误/异常
如果通过method参数传递的是一个未知的加密算法,将会抛出一个 E_WARNING 等级的错误。
如果通过iv参数传递的是一个空值,将会抛出一个 E_WARNING 等级的错误。
实例
<?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";
}
?>