AopEncrypt.php 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. <?php
  2. /**
  3. * 加密工具类
  4. *
  5. * User: jiehua
  6. * Date: 16/3/30
  7. * Time: 下午3:25
  8. */
  9. /**
  10. * 加密方法
  11. * @param string $str
  12. * @return string
  13. */
  14. function encrypt($str, $screct_key)
  15. {
  16. //AES, 128 模式加密数据 CBC
  17. $screct_key = base64_decode($screct_key);
  18. $str = trim($str);
  19. $str = addPKCS7Padding($str);
  20. //设置全0的IV
  21. $iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
  22. $iv = str_repeat("\0", $iv_size);
  23. $encrypt_str = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $screct_key, $str, MCRYPT_MODE_CBC, $iv);
  24. return base64_encode($encrypt_str);
  25. }
  26. /**
  27. * 解密方法
  28. * @param string $str
  29. * @return string
  30. */
  31. function decrypt($str, $screct_key)
  32. {
  33. //AES, 128 模式加密数据 CBC
  34. $str = base64_decode($str);
  35. $screct_key = base64_decode($screct_key);
  36. //设置全0的IV
  37. $iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
  38. $iv = str_repeat("\0", $iv_size);
  39. $decrypt_str = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $screct_key, $str, MCRYPT_MODE_CBC, $iv);
  40. $decrypt_str = stripPKSC7Padding($decrypt_str);
  41. return $decrypt_str;
  42. }
  43. /**
  44. * 填充算法
  45. * @param string $source
  46. * @return string
  47. */
  48. function addPKCS7Padding($source)
  49. {
  50. $source = trim($source);
  51. $block = mcrypt_get_block_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
  52. $pad = $block - (strlen($source) % $block);
  53. if ($pad <= $block) {
  54. $char = chr($pad);
  55. $source .= str_repeat($char, $pad);
  56. }
  57. return $source;
  58. }
  59. /**
  60. * 移去填充算法
  61. * @param string $source
  62. * @return string
  63. */
  64. function stripPKSC7Padding($source)
  65. {
  66. $char = substr($source, -1);
  67. $num = ord($char);
  68. if ($num == 62) return $source;
  69. $source = substr($source, 0, -$num);
  70. return $source;
  71. }