No Description

AopEncrypt.php 1.6KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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. //AES, 128 模式加密数据 CBC
  16. $screct_key = base64_decode($screct_key);
  17. $str = trim($str);
  18. $str = addPKCS7Padding($str);
  19. $iv = mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128,MCRYPT_MODE_CBC),1);
  20. $encrypt_str = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $screct_key, $str, MCRYPT_MODE_CBC);
  21. return base64_encode($encrypt_str);
  22. }
  23. /**
  24. * 解密方法
  25. * @param string $str
  26. * @return string
  27. */
  28. function decrypt($str,$screct_key){
  29. //AES, 128 模式加密数据 CBC
  30. $str = base64_decode($str);
  31. $screct_key = base64_decode($screct_key);
  32. $iv = mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128,MCRYPT_MODE_CBC),1);
  33. $encrypt_str = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $screct_key, $str, MCRYPT_MODE_CBC);
  34. $encrypt_str = trim($encrypt_str);
  35. $encrypt_str = stripPKSC7Padding($encrypt_str);
  36. return $encrypt_str;
  37. }
  38. /**
  39. * 填充算法
  40. * @param string $source
  41. * @return string
  42. */
  43. function addPKCS7Padding($source){
  44. $source = trim($source);
  45. $block = mcrypt_get_block_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
  46. $pad = $block - (strlen($source) % $block);
  47. if ($pad <= $block) {
  48. $char = chr($pad);
  49. $source .= str_repeat($char, $pad);
  50. }
  51. return $source;
  52. }
  53. /**
  54. * 移去填充算法
  55. * @param string $source
  56. * @return string
  57. */
  58. function stripPKSC7Padding($source){
  59. $source = trim($source);
  60. $char = substr($source, -1);
  61. $num = ord($char);
  62. if($num==62)return $source;
  63. $source = substr($source,0,-$num);
  64. return $source;
  65. }