首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

openssl_encrypt

(PHP 5 >= 5.3.0, PHP 7)

openssl_encrypt — 加密数据

描述

代码语言:javascript
复制
string openssl_encrypt ( string $data , string $method , string $key [, int $options = 0 [, string $iv = "" [, string &$tag = NULL [, string $aad = "" [, int $tag_length = 16 ]]]]] )

使用给定的方法和密钥加密给定的数据,返回一个原始或base64编码的字符串

参数

data

明文消息数据要加密。

method

密码方法。有关可用密码方法的列表,请使用openssl_get_cipher_methods()。

key

The key.

options

options是一个按位分隔的标志OPENSSL_RAW_DATAOPENSSL_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已更改为选项。

7.1.0

添加了标签,aad和tag_length参数。

例子

示例#1在GCM模式下的AES身份验证加密示例适用于PHP 7.1及更高版本

代码语言:javascript
复制
<?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身份验证加密示例

代码语言:javascript
复制
<?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";
}
?>

扫码关注腾讯云开发者

领取腾讯云代金券

http://www.vxiaotou.com