当前位置:Gxlcms > PHP教程 > PHP后端使用AES加密解密类

PHP后端使用AES加密解密类

时间:2021-07-01 10:21:17 帮助过:18人阅读

本篇文章介绍的内容是PHP后端使用AES加密解密类 ,现在分享给大家,有需要的朋友可以参考一下


  1. <?php
  2. namespace app\common\lib;
  3. /**
  4. * aes 加密 解密类库
  5. * @by singwa
  6. * Class Aes
  7. * @package app\common\lib
  8. */
  9. class Aes {
  10. private $key = null;
  11. /**
  12. *
  13. * @param $key
  14. 密钥
  15. * @return String
  16. */
  17. public function __construct() {
  18. // 需要小伙伴在配置文件app.php中定义aeskey
  19. $this->key = config('app.aeskey');
  20. }
  21. /**
  22. * 加密
  23. * @param String input 加密的字符串
  24. * @param String key 解密的key
  25. * @return HexString
  26. */
  27. public function encrypt($input = '') {
  28. $size = mcrypt_get_block_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_ECB);
  29. $input = $this->pkcs5_pad($input, $size);
  30. $td = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_ECB, '');
  31. $iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
  32. mcrypt_generic_init($td, $this->key, $iv);
  33. $data = mcrypt_generic($td, $input);
  34. mcrypt_generic_deinit($td);
  35. mcrypt_module_close($td);
  36. $data = base64_encode($data);
  37. return $data;
  38. }
  39. /**
  40. * 填充方式 pkcs5
  41. * @param String text
  42. 原始字符串
  43. * @param String blocksize 加密长度
  44. * @return String
  45. */
  46. private function pkcs5_pad($text, $blocksize) {
  47. $pad = $blocksize - (strlen($text) % $blocksize);
  48. return $text . str_repeat(chr($pad), $pad);
  49. }
  50. /**
  51. * 解密
  52. * @param String input 解密的字符串
  53. * @param String key 解密的key
  54. * @return String
  55. */
  56. public function decrypt($sStr) {
  57. $decrypted= mcrypt_decrypt(MCRYPT_RIJNDAEL_128,$this->key,base64_decode($sStr), MCRYPT_MODE_ECB);
  58. $dec_s = strlen($decrypted);
  59. $padding = ord($decrypted[$dec_s-1]);
  60. $decrypted = substr($decrypted, 0, -$padding);
  61. return $decrypted;
  62. }
  63. }

相关推荐:

php如通过AES加密/解密实现bin2hex和hex2bin之间的切换

php实现AES加密类定义与用法

以上就是PHP后端使用AES加密解密类 的详细内容,更多请关注Gxl网其它相关文章!

人气教程排行