Aes.php 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. <?php
  2. namespace App\Services;
  3. class Aes
  4. {
  5. /**
  6. * 加密
  7. * @param string $sSrc 待加密字符串
  8. * @param string $sKey 秘钥
  9. * @return string
  10. */
  11. public static function encrypt($sSrc, $sKey) {
  12. if ($sKey === null) {
  13. return null;
  14. }
  15. // Java 的 PKCS5Padding 在 PHP OpenSSL 中等同于默认的 PKCS7 填充
  16. // AES-128-ECB 会根据 key 的长度自动调整,但通常建议 key 为 16 位
  17. $encrypted = openssl_encrypt($sSrc, 'aes-256-ecb', $sKey, OPENSSL_RAW_DATA);
  18. // 使用 Base64 编码返回
  19. return base64_encode($encrypted);
  20. }
  21. /**
  22. * 解密
  23. * @param string $sSrc 加密后的 Base64 字符串
  24. * @param string $sKey 秘钥
  25. * @return string
  26. */
  27. public static function decrypt($sSrc, $sKey) {
  28. if ($sKey === null) {
  29. return null;
  30. }
  31. // 先进行 Base64 解码
  32. $decrypted1 = base64_decode($sSrc);
  33. // 执行解密
  34. $original = openssl_decrypt($decrypted1, 'aes-256-ecb', $sKey, OPENSSL_RAW_DATA);
  35. return $original;
  36. }
  37. }