php 纯数字 对称加密,PHP AES对称加密算法

利用php加密库 mcrypt 进行AES加密解密

//AES加密类

class AESMcrypt {

public $iv = null; //秘钥向量

public $key = null; //加密key

public $bit = 128;

public $mode= null;//加密模式

private $cipher;

public function __construct($bit, $key, $iv, $mode) {

if(empty($bit) || empty($key) || empty($iv) || empty($mode)){

return NULL;

}

$this->bit = $bit;

$this->key = $key;

$this->iv = $iv;

$this->mode = $mode;

switch($this->bit) {

case 192:$this->cipher = MCRYPT_RIJNDAEL_192; break;

case 256:$this->cipher = MCRYPT_RIJNDAEL_256; break;

default: $this->cipher = MCRYPT_RIJNDAEL_128;

}

switch($this->mode) {

case 'ecb':$this->mode = MCRYPT_MODE_ECB; break;

case 'cfb':$this->mode = MCRYPT_MODE_CFB; break;

case 'ofb':$this->mode = MCRYPT_MODE_OFB; break;

case 'nofb':$this->mode = MCRYPT_MODE_NOFB; break;

case 'cbc':$this->mode = MCRYPT_MODE_CBC; break;

default: $this->mode = MCRYPT_MODE_CBC;

}

}

public function encrypt($data) {

$data = base64_encode(mcrypt_encrypt( $this->cipher, $this->key, $data, $this->mode, $this->iv));

return $data;

}

public function decrypt($data) {

$data = mcrypt_decrypt( $this->cipher, $this->key, base64_decode($data), $this->mode, $this->iv);

$data = rtrim(rtrim($data), "\x00..\x1F");

return $data;

}

}

在ThinkPHP3.2中的使用方法

把加密类放在第三方类库目录中

3e4cacf2f484

image.png

在公共函数中调用

/**

* AES加密

* @param [string] $str 要加密的字符串

* @return [string] $str 加密后的字符串

*/

function encrypt($str){

Vendor('AES.AESMcrypt');

$config = C('AES');

$bit = $config['bit'];

$key = $config['key'];

$iv = $config['iv'];

$mode = $config['mode'];

$aes = new AESMcrypt($bit, $key, $iv,$mode);

$str = $aes->encrypt($str);

return $str;

}

/**

* AES解密

* @param [string] $str 要解密的字符串

* @return [string] $str 解密后的字符串

*/

function decrypt($str){

Vendor('AES.AESMcrypt');

$config = C('AES');//config中的配置

$bit = $config['bit'];

$key = $config['key'];

$iv = $config['iv'];

$mode = $config['mode'];

$aes = new AESMcrypt($bit, $key, $iv,$mode);

$str = $aes->decrypt($str);

return $str;

}

config配置文件

//注意cbc模式key和iv必须是长度为16的字符串

'AES' => array(

'bit' => 128,

'key' => 'woshiwangjiewang',//加解密key

'iv' => 'wangjieshiwowang',//秘钥向量

'mode' => 'cbc',//加密模式

),

接下来就可以在ThinkPHP中的直接调用encrypt()和decrypt()传入字符串进行加密解密了。

encrypt('我是王杰');

加密后

// WLnz+cbKlkoI40BD8R4e/Q==

decrypt('WLnz+cbKlkoI40BD8R4e/Q==');

解密后

我是王杰

可以用下面的代码来检测系统是否安装了 mcrypt 模块,并查看支持哪些加密算法和模式

$cipher_list = mcrypt_list_algorithms();//mcrypt支持的加密算法列表

$mode_list = mcrypt_list_modes(); //mcrypt支持的加密模式列表

var_dump($cipher_list);

var_dump($mode_list);

我当前的PHP支持一下算法和模式

3e4cacf2f484

image.png

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值