对称加密是一种加密方式,其加密和解密使用的密钥是相同的。在PHP中,可以使用多种函数来实现对称加密,其中常用的有openssl_encrypt和openssl_decrypt函数。
openssl_encrypt函数用于加密数据。它的语法如下:
```
string openssl_encrypt ( string $data , string $method , string $password [, int $options = 0 [, string $iv = "" [, string &$tag = NULL [, string $aad = "" [, int $tag_length = 16 ]]]]] )
```
这个函数的参数包括:
- data:需要加密的数据。
- method:加密算法,例如AES-256-CBC。
- password:加密使用的密码。
- options:可选参数,指定加密时的选项。
- iv:可选参数,初始化向量。
- tag:可选参数,用于存储认证标签。
- aad:可选参数,附加的验证数据。
- tag_length:可选参数,认证标签的长度。
下面是一个使用openssl_encrypt函数进行AES对称加密的例子:
```php
$data = 'Hello, world!';
$method = 'AES-256-CBC';
$password = '1234567890';
$iv_length = openssl_cipher_iv_length($method);
$iv = openssl_random_pseudo_bytes($iv_length);
$encrypted_data = openssl_encrypt($data, $method, $password, OPENSSL_RAW_DATA, $iv);
echo base64_encode($encrypted_data);
```
在这个例子中,我们将字符串"Hello, world!"进行了AES-256-CBC对称加密。加密使用的密码是"1234567890",初始化向量是通过openssl_random_pseudo_bytes函数生成的随机字节序列。最后,我们使用base64_encode函数将加密后的数据转换成Base64编码的字符串输出。
解密加密数据可以使用openssl_decrypt函数。它的语法如下:
```
string openssl_decrypt ( string $data , string $method , string $password [, int $options = 0 [, string $iv = "" [, string $tag = NULL [, string $aad = "" ]]]] )
```
这个函数的参数与openssl_encrypt函数类似。下面是一个使用openssl_decrypt函数解密上面加密的数据的例子:
```php
$encrypted_data = base64_decode($encrypted_data);
$decrypted_data = openssl_decrypt($encrypted_data, $method, $password, OPENSSL_RAW_DATA, $iv);
echo $decrypted_data;
```
在这个例子中,我们将前面加密得到的Base64编码的字符串解码成二进制数据,并使用openssl_decrypt函数对数据进行解密。解密使用的参数与加密时相同,包括密码和初始化向量。
除了openssl_encrypt和openssl_decrypt函数以外,PHP还提供了其他一些对称加密相关的函数,例如mcrypt_encrypt和mcrypt_decrypt函数。但是,从PHP7.1开始,mcrypt函数库已被废弃,不再推荐使用。
总结来说,对称加密是一种简单且高效的加密方式,在PHP中可以使用openssl_encrypt和openssl_decrypt函数来实现对称加密。 如果你喜欢我们三七知识分享网站的文章, 欢迎您分享或收藏知识分享网站文章 欢迎您到我们的网站逛逛喔!https://www.ynyuzhu.com/
发表评论 取消回复