AopEncrypt.php 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  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 = str_repeat("\0", 16);
  22. $encrypt_str = openssl_encrypt($str, 'aes-128-cbc', $screct_key, OPENSSL_NO_PADDING, $iv);
  23. return base64_encode($encrypt_str);
  24. }
  25. /**
  26. * 解密方法
  27. * @param string $str
  28. * @return string
  29. */
  30. function decrypt($str, $screct_key)
  31. {
  32. //AES, 128 模式加密数据 CBC
  33. $str = base64_decode($str);
  34. $screct_key = base64_decode($screct_key);
  35. //设置全0的IV
  36. $iv = str_repeat("\0", 16);
  37. $decrypt_str = openssl_decrypt($str, 'aes-128-cbc', $screct_key, OPENSSL_NO_PADDING, $iv);
  38. $decrypt_str = stripPKSC7Padding($decrypt_str);
  39. return $decrypt_str;
  40. }
  41. /**
  42. * 填充算法
  43. * @param string $source
  44. * @return string
  45. */
  46. function addPKCS7Padding($source)
  47. {
  48. $source = trim($source);
  49. $block = 16;
  50. $pad = $block - (strlen($source) % $block);
  51. if ($pad <= $block) {
  52. $char = chr($pad);
  53. $source .= str_repeat($char, $pad);
  54. }
  55. return $source;
  56. }
  57. /**
  58. * 移去填充算法
  59. * @param string $source
  60. * @return string
  61. */
  62. function stripPKSC7Padding($source)
  63. {
  64. $char = substr($source, -1);
  65. $num = ord($char);
  66. if ($num == 62) return $source;
  67. $source = substr($source, 0, -$num);
  68. return $source;
  69. }