当前位置:Gxlcms > PHP教程 > AES

AES

时间:2021-07-01 10:21:17 帮助过:13人阅读

  1. class aes {
  2. static public $mode = MCRYPT_MODE_NOFB;
  3. static public function generateKey($length=32) {
  4. if (!in_array($length,array(16,24,32)))
  5. return False;
  6. $str = '';
  7. for ($i=0;$i<$length;$i++) {
  8. $str .= chr(rand(33,126));
  9. }
  10. return $str;
  11. }
  12. static public function encrypt($data, $key) {
  13. if (strlen($key) > 32 || !$key)
  14. return trigger_error('key too large or key is empty.', E_USER_WARNING) && False;
  15. $ivSize = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, self::$mode);
  16. $iv = mcrypt_create_iv($ivSize, (substr(PHP_OS,0,1) == 'W' ? MCRYPT_RAND : MCRYPT_DEV_URANDOM ));
  17. $encryptedData = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $key, $data, self::$mode, $iv);
  18. $encryptedData = $iv . $encryptedData;
  19. return base64_encode($encryptedData);
  20. }
  21. static public function decrypt($data, $key) {
  22. if (strlen($key) > 32 || !$key)
  23. return trigger_error('key too large or key is empty.', E_USER_WARNING) && False;
  24. $data = base64_decode($data);
  25. if (!$data)
  26. return False;
  27. $ivSize = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, self::$mode);
  28. $iv = substr($data, 0, $ivSize);
  29. $data = substr($data, $ivSize);
  30. $decryptData = mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $key, $data, self::$mode, $iv);
  31. return $decryptData;
  32. }}

AES

人气教程排行