欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  后端开发

PHP aes算法

程序员文章站 2022-06-05 18:01:53
...
PHP aes算法




  1. function aes128cbcEncrypt($key, $text)
  2. {
  3. /**
  4. * Open the cipher
  5. */
  6. $td = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_CBC, '');
  7. if (! $td)
  8. {
  9. throw new GeneralSecurityException('Invalid mcrypt cipher, check your libmcrypt library and php-mcrypt extention');
  10. }
  11. // replaced MCRYPT_DEV_RANDOM with MCRYPT_RAND since windows doesn't have /dev/rand :)
  12. srand((double)microtime() * 1000000);
  13. $iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
  14. /**
  15. * Intialize encryption
  16. */
  17. mcrypt_generic_init($td, $key, $iv);
  18. /**
  19. * Encrypt data
  20. */
  21. $encrypted = mcrypt_generic($td, $text);
  22. /**
  23. * Terminate encryption handler
  24. */
  25. mcrypt_generic_deinit($td);
  26. /**
  27. * AES-128-CBC encryption. The IV is returned as the first 16 bytes
  28. * of the cipher text.
  29. */
  30. return $iv . $encrypted;
  31. }
  32. function aes128cbcDecrypt($key, $encrypted_text)
  33. {
  34. /**
  35. * Open the cipher
  36. */
  37. $td = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_CBC, '');
  38. if (is_callable('mb_substr'))
  39. {
  40. $iv = mb_substr($encrypted_text, 0, Crypto_CIPHER_BLOCK_SIZE, 'latin1');
  41. }
  42. else
  43. {
  44. $iv = substr($encrypted_text, 0, Crypto_CIPHER_BLOCK_SIZE);
  45. }
  46. /**
  47. * Initialize encryption module for decryption
  48. */
  49. mcrypt_generic_init($td, $key, $iv);
  50. /**
  51. * Decrypt encrypted string
  52. */
  53. if (is_callable('mb_substr'))
  54. {
  55. $encrypted = mb_substr($encrypted_text, Crypto_CIPHER_BLOCK_SIZE, mb_strlen($encrypted_text, 'latin1'), 'latin1');
  56. }
  57. else
  58. {
  59. $encrypted = substr($encrypted_text, Crypto_CIPHER_BLOCK_SIZE);
  60. }
  61. $decrypted = mdecrypt_generic($td, $encrypted);
  62. /**
  63. * Terminate decryption handle and close module
  64. */
  65. mcrypt_generic_deinit($td);
  66. mcrypt_module_close($td);
  67. /**
  68. * Show string
  69. */
  70. return trim($decrypted);
  71. }
  72. define('Crypto_CIPHER_BLOCK_SIZE', 16);
  73. $a = aes128cbcEncrypt('pass', 'this is text');
  74. echo base64_encode($a) . "/r/n";
  75. $b = aes128cbcDecrypt('pass', $a);
  76. echo $b . "/r/n";
  77. $c = aes128cbcDecrypt('pass', base64_decode(base64_encode($a)));
  78. echo $c . "/r/n";
  79. ?>
复制代码
相关标签: PHP aes算法