• php与java通用AES加密解密算法


    AES指高级加密标准(Advanced Encryption Standard),是当前最流行的一种密码算法,在web应用开发,特别是对外提供接口时经常会用到,下面是我整理的一套php与java通用的AES加密解密算法。

    php版代码如下:

      1 <?php
      2 class CryptAES
      3 {
      4     protected $cipher = MCRYPT_RIJNDAEL_128;
      5     protected $mode = MCRYPT_MODE_ECB;
      6     protected $pad_method = NULL;
      7     protected $secret_key = '';
      8     protected $iv = '';
      9  
     10     public function set_cipher($cipher)
     11     {
     12         $this->cipher = $cipher;
     13     }
     14  
     15     public function set_mode($mode)
     16     {
     17         $this->mode = $mode;
     18     }
     19  
     20     public function set_iv($iv)
     21     {
     22         $this->iv = $iv;
     23     }
     24  
     25     public function set_key($key)
     26     {
     27         $this->secret_key = $key;
     28     }
     29  
     30     public function require_pkcs5()
     31     {
     32         $this->pad_method = 'pkcs5';
     33     }
     34  
     35     protected function pad_or_unpad($str, $ext)
     36     {
     37         if ( is_null($this->pad_method) )
     38         {
     39             return $str;
     40         }
     41         else
     42         {
     43             $func_name = __CLASS__ . '::' . $this->pad_method . '_' . $ext . 'pad';
     44             if ( is_callable($func_name) )
     45             {
     46                 $size = mcrypt_get_block_size($this->cipher, $this->mode);
     47                 return call_user_func($func_name, $str, $size);
     48             }
     49         }
     50         return $str;
     51     }
     52  
     53     protected function pad($str)
     54     {
     55         return $this->pad_or_unpad($str, '');
     56     }
     57  
     58     protected function unpad($str)
     59     {
     60         return $this->pad_or_unpad($str, 'un');
     61     }
     62  
     63     public function encrypt($str)
     64     {
     65         $str = $this->pad($str);
     66         $td = mcrypt_module_open($this->cipher, '', $this->mode, '');
     67  
     68         if ( empty($this->iv) )
     69         {
     70             $iv = @mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
     71         }
     72         else
     73         {
     74             $iv = $this->iv;
     75         }
     76  
     77         mcrypt_generic_init($td, $this->secret_key, $iv);
     78         $cyper_text = mcrypt_generic($td, $str);
     79         $rt=base64_encode($cyper_text);
     80         //$rt = bin2hex($cyper_text);
     81         mcrypt_generic_deinit($td);
     82         mcrypt_module_close($td);
     83  
     84         return $rt;
     85     }
     86  
     87     public function decrypt($str){
     88         $td = mcrypt_module_open($this->cipher, '', $this->mode, '');
     89  
     90         if ( empty($this->iv) )
     91         {
     92             $iv = @mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
     93         }
     94         else
     95         {
     96             $iv = $this->iv;
     97         }
     98  
     99         mcrypt_generic_init($td, $this->secret_key, $iv);
    100         //$decrypted_text = mdecrypt_generic($td, self::hex2bin($str));
    101         $decrypted_text = mdecrypt_generic($td, base64_decode($str));
    102         $rt = $decrypted_text;
    103         mcrypt_generic_deinit($td);
    104         mcrypt_module_close($td);
    105  
    106         return $this->unpad($rt);
    107     }
    108  
    109     public static function hex2bin($hexdata) {
    110         $bindata = '';
    111         $length = strlen($hexdata);
    112         for ($i=0; $i< $length; $i += 2)
    113         {
    114             $bindata .= chr(hexdec(substr($hexdata, $i, 2)));
    115         }
    116         return $bindata;
    117     }
    118  
    119     public static function pkcs5_pad($text, $blocksize)
    120     {
    121         $pad = $blocksize - (strlen($text) % $blocksize);
    122         return $text . str_repeat(chr($pad), $pad);
    123     }
    124  
    125     public static function pkcs5_unpad($text)
    126     {
    127         $pad = ord($text{strlen($text) - 1});
    128         if ($pad > strlen($text)) return false;
    129         if (strspn($text, chr($pad), strlen($text) - $pad) != $pad) return false;
    130         return substr($text, 0, -1 * $pad);
    131     }
    132 }
    133  
    134 $keyStr = 'UITN25LMUQC436IM';
    135 $plainText = 'this is a string will be AES_Encrypt';
    136  
    137 $aes = new CryptAES();
    138 $aes->set_key($keyStr);
    139 $aes->require_pkcs5();
    140 $encText = $aes->encrypt($plainText);
    141 $decString = $aes->decrypt($encText);
    142  
    143 echo $encText,"n",$decString;
    144  
    145 ?>

    运行结果:
    fhTD0NNIzv4jUEhJuC1htFFXJ/4S/rL6tDCJPiNvJ8mVLHWOD0HWweuxHynxoZf9
    this is a string will be AES_Encrypt

    java版代码如下:

     1 import java.security.Key; 
     2 import javax.crypto.Cipher; 
     3 import javax.crypto.spec.SecretKeySpec; 
     4  
     5 import org.apache.commons.codec.binary.Base64;
     6   
     7 public class CryptAES { 
     8   
     9     private static final String AESTYPE ="AES/ECB/PKCS5Padding"; 
    10  
    11     public static String AES_Encrypt(String keyStr, String plainText) { 
    12         byte[] encrypt = null; 
    13         try{ 
    14             Key key = generateKey(keyStr); 
    15             Cipher cipher = Cipher.getInstance(AESTYPE); 
    16             cipher.init(Cipher.ENCRYPT_MODE, key); 
    17             encrypt = cipher.doFinal(plainText.getBytes());     
    18         }catch(Exception e){ 
    19             e.printStackTrace(); 
    20         }
    21         return new String(Base64.encodeBase64(encrypt)); 
    22     } 
    23  
    24     public static String AES_Decrypt(String keyStr, String encryptData) {
    25         byte[] decrypt = null; 
    26         try{ 
    27             Key key = generateKey(keyStr); 
    28             Cipher cipher = Cipher.getInstance(AESTYPE); 
    29             cipher.init(Cipher.DECRYPT_MODE, key); 
    30             decrypt = cipher.doFinal(Base64.decodeBase64(encryptData)); 
    31         }catch(Exception e){ 
    32             e.printStackTrace(); 
    33         } 
    34         return new String(decrypt).trim(); 
    35     } 
    36  
    37     private static Key generateKey(String key)throws Exception{ 
    38         try{            
    39             SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(), "AES"); 
    40             return keySpec; 
    41         }catch(Exception e){ 
    42             e.printStackTrace(); 
    43             throw e; 
    44         } 
    45  
    46     } 
    47  
    48     public static void main(String[] args) { 
    49          
    50         String keyStr = "UITN25LMUQC436IM";  
    51  
    52         String plainText = "this is a string will be AES_Encrypt";
    53          
    54         String encText = AES_Encrypt(keyStr, plainText);
    55         String decString = AES_Decrypt(keyStr, encText); 
    56          
    57         System.out.println(encText); 
    58         System.out.println(decString); 
    59  
    60     } 
    61 }

    运行结果:
    fhTD0NNIzv4jUEhJuC1htFFXJ/4S/rL6tDCJPiNvJ8mVLHWOD0HWweuxHynxoZf9
    this is a string will be AES_Encrypt

  • 相关阅读:
    【Selenium】selenium中隐藏元素如何定位?
    【Mock】【接口测试】【面试】mock-server 环境搭建—加分项!
    【Mock】mock基础、简单的单元测试代码练习。
    【WebDriver】WebDriver 常用操作
    【Loadrunner】Loadrnner 参数化策略
    ES6系列_11之Set和WeakSet数据结构
    ES6系列_10之Symbol在对象中的作用
    ES6系列_9之对象
    ES6系列_8之函数和数组
    ES6系列_7之箭头函数和扩展
  • 原文地址:https://www.cnblogs.com/luojianqun/p/7010298.html
Copyright © 2020-2023  润新知