内容简介:上一篇文章讲到利用利用
上一篇文章讲到利用 mcrypt
对数据进行aes加密的方法,但是不支持 php 7.1.x版本,今天在stackoverflow上看到同样的问题,是使用 openssl
函数的处理方法,点击下面的链接 stackoverflow
查看问题,根据上面的问题整理出了一个简单的加密类,经测试完全符合业务需求,现在写出来,希望对以后的工作会有帮助。
利用 openssl
加密更简单,而且支持php7.1.x版本,基本可以用于所有版本的php程序。
<?php
class OpenSSLAES
{
/**
* var string $method 加解密方法,可通过openssl_get_cipher_methods()获得
*/
protected $method;
/**
* var string $secret_key 加解密的密钥
*/
protected $secret_key;
/**
* var string $iv 加解密的向量,有些方法需要设置比如CBC
*/
protected $iv;
/**
* var string $options (不知道怎么解释,目前设置为0没什么问题)
*/
protected $options;
/**
* 构造函数
*
* @param string $key 密钥
* @param string $method 加密方式
* @param string $iv iv向量
* @param mixed $options 还不是很清楚
*
*/
public function __construct($key, $method = 'AES-128-ECB', $iv = '', $options = 0)
{
// key是必须要设置的
$this->secret_key = isset($key) ? $key : exit('key为必须项');
$this->method = $method;
$this->iv = $iv;
$this->options = $options;
}
/**
* 加密方法,对数据进行加密,返回加密后的数据
*
* @param string $data 要加密的数据
*
* @return string
*
*/
public function encrypt($data)
{
return openssl_encrypt($data, $this->method, $this->secret_key, $this->options, $this->iv);
}
/**
* 解密方法,对数据进行解密,返回解密后的数据
*
* @param string $data 要解密的数据
*
* @return string
*
*/
public function decrypt($data)
{
return openssl_decrypt($data, $this->method, $this->secret_key, $this->options, $this->iv);
}
}
$aes = new OpenSSLAES('12345678');
$encrypted = $aes->encrypt('凭栏知潇雨');
// KSGYvH0GOzQULoLouXqPJA==
echo '要加密的字符串:凭栏知潇雨<br>加密后的字符串:', $encrypted, '<hr>';
$decrypted = $aes->decrypt($encrypted);
echo '要解密的字符串:', $encrypted, '<br>解密后的字符串:', $decrypted;
经测试,结果和使用 mcrypt
加密结果一致。
以上所述就是小编给大家介绍的《PHP进行AES/ECB/PKCS7 padding加密的例子(openssl)》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!
猜你喜欢:本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
Algorithms + Data Structures = Programs
Niklaus Wirth / Prentice Hall / 1975-11-11 / GBP 84.95
It might seem completely dated with all its examples written in the now outmoded Pascal programming language (well, unless you are one of those Delphi zealot trying to resist to the Java/.NET dominanc......一起来看看 《Algorithms + Data Structures = Programs》 这本书的介绍吧!