将以下JAVA代码转为PHP代码:import javax.crypto.Cipher; import javax.crypto.spec.SecretKeySpec; import java.util.Base64; public class AesTool { public static String encrypt(String str, String key) throws Exception { Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding"); SecretKeySpec keySpec = new SecretKeySpec(key.getBytes("UTF-8"), "AES"); cipher.init(Cipher.ENCRYPT_MODE, keySpec); byte[] result = cipher.doFinal(str.getBytes("UTF-8")); return Base64.getEncoder().encodeToString(result); } public static String decrypt(String base64Str, String key) throws Exception { Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding"); SecretKeySpec keySpec = new SecretKeySpec(key.getBytes("UTF-8"), "AES"); cipher.init(Cipher.DECRYPT_MODE, keySpec); byte[] decoded = cipher.doFinal(Base64.getDecoder().decode(base64Str)); return new String(decoded, "UTF-8"); } }
时间: 2024-03-26 13:39:18 浏览: 14
以下是将JAVA代码转换为PHP代码的示例:
```php
<?php
class AesTool {
public static function encrypt($str, $key) {
$cipher = "AES-128-ECB";
$ivlen = openssl_cipher_iv_length($cipher);
$iv = openssl_random_pseudo_bytes($ivlen);
$result = openssl_encrypt($str, $cipher, $key, OPENSSL_RAW_DATA, $iv);
return base64_encode($result);
}
public static function decrypt($base64Str, $key) {
$cipher = "AES-128-ECB";
$base64Str = base64_decode($base64Str);
$ivlen = openssl_cipher_iv_length($cipher);
$iv = openssl_random_pseudo_bytes($ivlen);
$decoded = openssl_decrypt($base64Str, $cipher, $key, OPENSSL_RAW_DATA, $iv);
return $decoded;
}
}
```
在这个PHP代码示例中,我们使用了openssl扩展来实现AES算法的加解密,使用的是128位密钥和ECB模式,并且使用PKCS5Padding对明文进行了补位。