No Description

MagicCrypt.php 1.9KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. <?php
  2. class Security {
  3. private static $iv = "0102030405060708";
  4. public static function encrypt($input, $key) {
  5. $key = base64_decode($key);
  6. $localIV = Security::$iv;
  7. $module = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_CBC, $localIV);
  8. mcrypt_generic_init($module, $key, $localIV);
  9. $size = mcrypt_get_block_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
  10. $input = Security::pkcs5_pad($input, $size);
  11. $data = mcrypt_generic($module, $input);
  12. mcrypt_generic_deinit($module);
  13. mcrypt_module_close($module);
  14. $data = base64_encode($data);
  15. return $data;
  16. }
  17. public static function hmac_md5($input, $key) {
  18. $key = base64_decode($key);
  19. return hash_hmac('md5', $input, $key,true);
  20. }
  21. private static function pkcs5_pad ($text, $blocksize) {
  22. $pad = $blocksize - (strlen($text) % $blocksize);
  23. return $text . str_repeat(chr($pad), $pad);
  24. }
  25. public static function decrypt($sStr, $key) {
  26. $key = base64_decode($key);
  27. $localIV = Security::$iv;
  28. $module = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_CBC, $localIV);
  29. mcrypt_generic_init($module, $key, $localIV);
  30. $encryptedData = base64_decode($sStr);
  31. $encryptedData = mdecrypt_generic($module, $encryptedData);
  32. $dec_s = strlen($encryptedData);
  33. $padding = ord($encryptedData[$dec_s-1]);
  34. $decrypted = substr($encryptedData, 0, -$padding);
  35. mcrypt_generic_deinit($module);
  36. mcrypt_module_close($module);
  37. if(!$decrypted){
  38. throw new Exception("Decrypt Error,Please Check SecretKey");
  39. }
  40. return $decrypted;
  41. }
  42. }
  43. ?>