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

PHP实现AES256加密算法实例_PHP

程序员文章站 2022-05-12 08:52:57
...
本文实例讲述了PHP实现AES256加密算法的方法,是较为常见的一种加密算法。分享给大家供大家参考。具体如下:

aes.class.php文件如下:

 6 && $i%$Nk == 4) { 
    $temp = self::subWord($temp); 
   } 
   for ($t=0; $t

aesctr.class.php文件如下:

>> operator nor unsigned ints 
  * 
  * @param a number to be shifted (32-bit integer) 
  * @param b number of bits to shift a to the right (0..31) 
  * @return  a right-shifted and zero-filled by b bits 
  */ 
 private static function urs($a, $b) { 
  $a &= 0xffffffff; $b &= 0x1f; // (bounds check) 
  if ($a&0x80000000 && $b>0) {  // if left-most bit set 
   $a = ($a>>1) & 0x7fffffff;  //  right-shift one bit & clear left-most bit 
   $a = $a >> ($b-1);      //  remaining right-shifts 
  } else {            // otherwise 
   $a = ($a>>$b);        //  use normal right-shift 
  }  
  return $a;  
 } 
}  
?>

Demo实例程序如下:

'; 
 
$mstr = AesCtr::encrypt('Hello World', 'key', 256); 
echo "Encrypt String : $mstr
"; $dstr = AesCtr::decrypt($mstr, 'key', 256); echo "Decrypt String : $dstr
"; echo 'each not change
'; $mstr = AesCtr::encrypt('Hello World', 'key', 256, 1); // keep=1 echo "Encrypt String : $mstr
"; $dstr = AesCtr::decrypt($mstr, 'key', 256); echo "Decrypt String : $dstr
"; ?>

这里再介绍另一使用 PHP mcrypt 加解密方法:

/* aes 256 encrypt 
* @param String $ostr 
* @param String $securekey 
* @param String $type encrypt, decrypt 
*/ 
function aes($ostr, $securekey, $type='encrypt'){ 
  if($ostr==''){ 
    return ''; 
  } 
   
  $key = $securekey; 
  $iv = strrev($securekey); 
  $td = mcrypt_module_open('rijndael-256', '', 'ofb', ''); 
  mcrypt_generic_init($td, $key, $iv); 
 
  $str = ''; 
 
  switch($type){ 
    case 'encrypt': 
      $str = base64_encode(mcrypt_generic($td, $ostr)); 
      break; 
 
    case 'decrypt': 
      $str = mdecrypt_generic($td, base64_decode($ostr)); 
      break; 
  } 
 
  mcrypt_generic_deinit($td); 
 
  return $str; 
} 
 
// Demo 
$key = "fdipzone201314showmethemoney!@#$"; 
$str = "show me the money"; 
 
$ostr = aes($str, $key); 
echo "String 1: $ostr
"; $dstr = aes($ostr, $key, 'decrypt'); echo "String 2: $dstr
";

希望本文所述对大家php程序设计的学习有所帮助。