| 123456789101112131415161718192021222324252627282930313233343536373839404142434445 |
- <?php
- namespace App\Services;
- class Aes
- {
- /**
- * 加密
- * @param string $sSrc 待加密字符串
- * @param string $sKey 秘钥
- * @return string
- */
- public static function encrypt($sSrc, $sKey) {
- if ($sKey === null) {
- return null;
- }
- // Java 的 PKCS5Padding 在 PHP OpenSSL 中等同于默认的 PKCS7 填充
- // AES-128-ECB 会根据 key 的长度自动调整,但通常建议 key 为 16 位
- $encrypted = openssl_encrypt($sSrc, 'aes-256-ecb', $sKey, OPENSSL_RAW_DATA);
- // 使用 Base64 编码返回
- return base64_encode($encrypted);
- }
- /**
- * 解密
- * @param string $sSrc 加密后的 Base64 字符串
- * @param string $sKey 秘钥
- * @return string
- */
- public static function decrypt($sSrc, $sKey) {
- if ($sKey === null) {
- return null;
- }
- // 先进行 Base64 解码
- $decrypted1 = base64_decode($sSrc);
- // 执行解密
- $original = openssl_decrypt($decrypted1, 'aes-256-ecb', $sKey, OPENSSL_RAW_DATA);
- return $original;
- }
- }
|