PHPTS:一键免费搭建 Nginx + PHP + MySQL 运行环境

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

以指定的方式和 key 加密数据,返回原始或 base64 编码后的字符串。

参数

data

待加密的明文信息数据。

method

密码学方式。openssl_get_cipher_methods() 可获取有效密码方式列表。

key

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 级别的错误。

更新日志

版本 说明
5.3.3 增加 iv 参数。
5.4.0 raw_output 改到 options。
7.1.0 增加了 tag、aad、tag_length 参数

范例

Example #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";
}
?>

Example #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";
}
?>

参见