php写的AES加密解密类分享

前端之家收集整理的这篇文章主要介绍了php写的AES加密解密类分享前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

今天写了一个PHP的AES加密类。适用于Yii的扩展。 如果不用在Yii框架中,把代码中Yii::app()->params['encryptKey'] 换成你对应的默认key就可以了。 类代码:

PHP;"> params['encryptKey'] : $key,mcrypt_enc_get_key_size($module)); /* Create the IV and determine the keysize length,use MCRYPT_RAND * on Windows instead */ $iv = substr(md5($key),mcrypt_enc_get_iv_size($module)); /* Intialize encryption */ mcrypt_generic_init($module,$key,$iv);
  1. /* Encrypt data */
  2. $encrypted = mcrypt_generic($module,$plaintext);
  3. /* Terminate encryption handler */
  4. mcrypt_generic_deinit($module);
  5. mcrypt_module_close($module);
  6. return base64_encode($encrypted);
  7. }
  8. /**
  9. * This was AES-128 / CBC / NoPadding decrypted.
  10. * @author Terry
  11. * @param string $encrypted base64_encode encrypted string
  12. * @param string $key
  13. * @throws CException
  14. * @return string
  15. */
  16. public static function AesDecrypt($encrypted,$key = null)
  17. {
  18. if ($encrypted == '') return '';
  19. if(!extension_loaded('mcrypt'))
  20. throw new CException(Yii::t('yii','AesDecrypt requires <a href="/tag/PHP/" target="_blank" class="keywords">PHP</a> mcrypt extension to be loaded in order to use data encryption feature.'));
  21. $ciphertext_dec = base64_decode($encrypted);
  22. $module = mcrypt_module_open(MCRYPT_RIJNDAEL_128,mcrypt_enc_get_key_size($module));
  23. $iv = substr(md5($key),mcrypt_enc_get_iv_size($module));
  24. /* Initialize encryption module for decryption */
  25. mcrypt_generic_init($module,$iv);
  26. /* Decrypt encrypted string */
  27. $decrypted = mdecrypt_generic($module,$ciphertext_dec);
  28. /* Terminate decryption handle and close module */
  29. mcrypt_generic_deinit($module);
  30. mcrypt_module_close($module);
  31. return rtrim($decrypted,"\0");
  32. }
  33. /**
  34. * Returns the length of the given string.
  35. * If available uses the multibyte string function mb_strlen.
  36. * @param string $string the string being measured for length
  37. * @return integer the length of the string
  38. */
  39. private static function strlen($string)
  40. {
  41. return extension_loaded('mbstring') ? mb_strlen($string,'8bit') : strlen($string);
  42. }
  43. /**
  44. * Returns the portion of string specified by the start and length parameters.
  45. * If available uses the multibyte string function mb_substr
  46. * @param string $string the input string. Must be one character or longer.
  47. * @param integer $start the starting position
  48. * @param integer $length the desired portion length
  49. * @return string the extracted part of string,or FALSE on failure or an empty string.
  50. */
  51. private static function substr($string,$start,$length)
  52. {
  53. return extension_loaded('mbstring') ? mb_substr($string,$length,'8bit') : substr($string,$length);
  54. }

}

猜你在找的PHP相关文章