要在PHP中实现与Java AES加密相同的功能,你需要确保加密算法、模式、填充方式以及密钥和IV(初始化向量)在Java和PHP中保持一致。以下是一个示例,展示如何在Java和PHP中使用AES加密。
假设你在Java中使用AES加密,代码如下:
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
public class AESExample {
public static void main(String[] args) throws Exception {
String key = "1234567890123456"; // 16字节的密钥
String iv = "1234567890123456"; // 16字节的IV
String plainText = "Hello, World!";
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(), "AES");
IvParameterSpec ivParameterSpec = new IvParameterSpec(iv.getBytes());
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivParameterSpec);
byte[] encrypted = cipher.doFinal(plainText.getBytes());
String encryptedText = Base64.getEncoder().encodeToString(encrypted);
System.out.println("Encrypted: " + encryptedText);
}
}
在PHP中,你可以使用openssl_encrypt
函数来实现相同的AES加密。以下是PHP代码:
<?php
$key = "1234567890123456"; // 16字节的密钥
$iv = "1234567890123456"; // 16字节的IV
$plainText = "Hello, World!";
// 使用AES-128-CBC加密
$encrypted = openssl_encrypt($plainText, 'AES-128-CBC', $key, OPENSSL_RAW_DATA, $iv);
// 将加密后的数据转换为Base64编码
$encryptedText = base64_encode($encrypted);
echo "Encrypted: " . $encryptedText . "\n";
?>
算法和模式:在Java中使用的是AES/CBC/PKCS5Padding
,在PHP中对应的模式是AES-128-CBC
。AES-128
表示使用128位密钥的AES算法,CBC
是加密模式,PKCS5Padding
是填充方式。
密钥和IV:密钥和IV的长度必须与算法要求一致。对于AES-128,密钥和IV都必须是16字节(128位)。
Base64编码:加密后的数据是二进制数据,通常需要转换为Base64编码以便于传输和存储。
如果你需要在PHP中解密Java加密的数据,可以使用openssl_decrypt
函数:
<?php
$key = "1234567890123456"; // 16字节的密钥
$iv = "1234567890123456"; // 16字节的IV
$encryptedText = "your_encrypted_text_here"; // 从Java加密得到的Base64编码字符串
// 将Base64编码的字符串解码为二进制数据
$encrypted = base64_decode($encryptedText);
// 使用AES-128-CBC解密
$decrypted = openssl_decrypt($encrypted, 'AES-128-CBC', $key, OPENSSL_RAW_DATA, $iv);
echo "Decrypted: " . $decrypted . "\n";
?>
通过确保Java和PHP中的加密算法、模式、填充方式、密钥和IV一致,你可以在两种语言之间实现AES加密和解密的互操作性。