欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

php实现aes加密类分享

程序员文章站 2023-11-26 14:41:40
复制代码 代码如下:

复制代码 代码如下:

<?php

class aesmcrypt {

 public $iv = null;
 public $key = null;
 public $bit = 128;
 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;
   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;
 }

}

//使用方法
$aes = new aesmcrypt($bit = 128, $key = 'abcdef1234567890', $iv = '0987654321fedcba', $mode = 'cbc');
$c = $aes->encrypt('haowei.me');
var_dump($aes->decrypt($c));