helper.php 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. <?php
  2. declare(strict_types=1);
  3. if (!function_exists('encrypt_data')) {
  4. /**
  5. * 使用AES-256-CBC加密数据
  6. *
  7. * @param string $data 待加密的数据
  8. * @param string $key 加密密钥
  9. * @return string Base64编码后的加密结果
  10. */
  11. function encrypt_data(string $data, string $key): string
  12. {
  13. // 生成16字节IV
  14. $iv = openssl_random_pseudo_bytes(16);
  15. // 加密数据
  16. $encrypted = openssl_encrypt($data, 'aes-256-cbc', $key, OPENSSL_RAW_DATA, $iv);
  17. // 组合IV和密文并进行Base64编码
  18. return base64_encode($iv . $encrypted);
  19. }
  20. }
  21. // 检查函数是否已存在,避免重复定义
  22. if (!function_exists('decrypt_data')) {
  23. /**
  24. * 使用AES-256-CBC解密数据
  25. *
  26. * @param string $result Base64编码后的加密结果
  27. * @param string $key 解密密钥
  28. * @return string 解密后的原始数据
  29. */
  30. function decrypt_data(string $result, string $key): string
  31. {
  32. // Base64解码
  33. $data = base64_decode($result);
  34. // 提取IV和密文
  35. $iv = substr($data, 0, 16);
  36. $ciphertext = substr($data, 16);
  37. // 解密数据
  38. return openssl_decrypt($ciphertext, 'aes-256-cbc', $key, OPENSSL_RAW_DATA, $iv);
  39. }
  40. }