使用AES进行加密


<?php
namespace app\common\lib;

/**

  • aes 加密 解密类库

  • @by singwa

  • Class Aes

  • @package app\common\lib
    */
    class Aes {

    private $key = null;

    /**
    *

    • @param $key 密钥
    • @return String
      */
      public function __construct() {
      // 需要小伙伴在配置文件app.php中定义aeskey
      $this->key = config(‘app.aes_key’);
      }

    /**

    • 加密

    • @param String input 加密的字符串

    • @param String key 解密的key

    • @return HexString
      */
      public function encrypt($input = ‘’) {
      $size = mcrypt_get_block_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_ECB);
      $input = t h i s &gt; p k c s 5 p a d ( this-&gt;pkcs5_pad( input, $size);
      $td = mcrypt_module_open(MCRYPT_RIJNDAEL_128, ‘’, MCRYPT_MODE_ECB, ‘’);
      i v = m c r y p t c r e a t e i v ( m c r y p t e n c g e t i v s i z e ( iv = mcrypt_create_iv(mcrypt_enc_get_iv_size( td), MCRYPT_RAND);
      mcrypt_generic_init($td, $this->key, $iv);

      d a t a = m c r y p t g e n e r i c ( data = mcrypt_generic( td, i n p u t ) ; m c r y p t g e n e r i c d e i n i t ( input); mcrypt_generic_deinit( td);
      mcrypt_module_close($td);
      d a t a = b a s e 6 4 e n c o d e ( data = base64_encode( data);

      return $data;

    }
    /**

    • 填充方式 pkcs5
    • @param String text 原始字符串
    • @param String blocksize 加密长度
    • @return String
      */
      private function pkcs5_pad($text, $blocksize) {
      $pad = b l o c k s i z e ( s t r l e n ( blocksize - (strlen( text) % $blocksize);
      return t e x t . s t r r e p e a t ( c h r ( text . str_repeat(chr( pad), $pad);
      }

    /**

    • 解密

    • @param String input 解密的字符串

    • @param String key 解密的key

    • @return String
      */
      public function decrypt($sStr) {
      d e c r y p t e d = m c r y p t d e c r y p t ( M C R Y P T R I J N D A E L 1 28 , decrypted= mcrypt_decrypt(MCRYPT_RIJNDAEL_128, this->key,base64_decode($sStr), MCRYPT_MODE_ECB);
      d e c s = s t r l e n ( dec_s = strlen( decrypted);
      p a d d i n g = o r d ( padding = ord( decrypted[$dec_s-1]);
      d e c r y p t e d = s u b s t r ( decrypted = substr( decrypted, 0, -$padding);

      return $decrypted;
      }

}

猜你喜欢

转载自blog.csdn.net/qq_33113113/article/details/83046361