同樣是 AES-128-ECB-PKCS5Padding,PHP mcrypt/openssl 與 Java Cipher 經常產生不同密文,主因在於:
SecretKeySpec 用 byte[],編碼/截斷/補零邏輯不同mcrypt 要求提供、Java 忽略mcrypt 需手動 PKCS7,Java 內建 PKCS5Padding| 參數 | 規範值 | 說明 |
|---|---|---|
| 演算法 | AES-128-ECB | 或 AES-256-CBC (需 IV) |
| Key | 16/32 bytes UTF-8 bytes | 不足補 \0,超過截斷 |
| 填充 | PKCS#7 (PKCS5Padding) | Java 標準名,PHP 需手動實現 |
| 輸出編碼 | Base64 (標準 RFC4648) | 無換行、無空格 |
| 字元編碼 | UTF-8 | 明文/密文轉 bytes 統一用 UTF-8 |
<?php
class AesCrypt {
private $key;
private $method;
private $options;
public function __construct(string $key, string $method = 'AES-128-ECB') {
// Key 正規化:UTF-8 bytes,截斷/補零到指定長度
$keyLen = match($method) {
'AES-128-ECB', 'AES-128-CBC' => 16,
'AES-192-ECB', 'AES-192-CBC' => 24,
'AES-256-ECB', 'AES-256-CBC' => 32,
default => 16
};
$this->key = mb_substr($key, 0, $keyLen, '8bit');
$this->key = str_pad($this->key, $keyLen, "\0", STR_PAD_RIGHT);
$this->method = $method;
$this->options = OPENSSL_RAW_DATA | OPENSSL_ZERO_PADDING; // 手動處理填充
}
// PKCS#7 填充
private function pkcs7Pad(string $data, int $blockSize = 16): string {
$padLen = $blockSize - (strlen($data) % $blockSize);
return $data . str_repeat(chr($padLen), $padLen);
}
// PKCS#7 去填充
private function pkcs7Unpad(string $data): string {
$padLen = ord($data[strlen($data) - 1]);
if ($padLen < 1 || $padLen > 16) throw new Exception('Invalid padding');
return substr($data, 0, -$padLen);
}
public function encrypt(string $plaintext): string {
$padded = $this->pkcs7Pad($plaintext);
$encrypted = openssl_encrypt($padded, $this->method, $this->key, $this->options);
if ($encrypted === false) throw new Exception('Encryption failed: ' . openssl_error_string());
return base64_encode($encrypted);
}
public function decrypt(string $base64Ciphertext): string {
$decrypted = openssl_decrypt(base64_decode($base64Ciphertext), $this->method, $this->key, $this->options);
if ($decrypted === false) throw new Exception('Decryption failed');
return $this->pkcs7Unpad($decrypted);
}
// CBC 模式需 IV
public function encryptCbc(string $plaintext, string $iv): string {
if (strlen($iv) !== 16) throw new Exception('IV must be 16 bytes');
$padded = $this->pkcs7Pad($plaintext);
$encrypted = openssl_encrypt($padded, $this->method, $this->key, OPENSSL_RAW_DATA, $iv);
return base64_encode($encrypted);
}
public function decryptCbc(string $base64Ciphertext, string $iv): string {
if (strlen($iv) !== 16) throw new Exception('IV must be 16 bytes');
$decrypted = openssl_decrypt(base64_decode($base64Ciphertext), $this->method, $this->key, OPENSSL_RAW_DATA, $iv);
return $this->pkcs7Unpad($decrypted);
}
}
// 測試
$key = '1234567891234567'; // 16 bytes
$aes = new AesCrypt($key, 'AES-128-ECB');
$data = 'example';
$encrypted = $aes->encrypt($data);
$decrypted = $aes->decrypt($encrypted);
echo "PHP Encrypt: $encrypted\n";
echo "PHP Decrypt: $decrypted\n";
// 輸出應與 Java 端一致
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
public class AesCrypt {
private final SecretKeySpec keySpec;
private final String transformation;
public AesCrypt(String key, String transformation) {
// Key 處理:UTF-8 bytes,截斷/補零
byte[] keyBytes = key.getBytes(StandardCharsets.UTF_8);
int keyLen = transformation.contains("128") ? 16 :
transformation.contains("192") ? 24 : 32;
byte[] normalizedKey = new byte[keyLen];
System.arraycopy(keyBytes, 0, normalizedKey, 0, Math.min(keyBytes.length, keyLen));
this.keySpec = new SecretKeySpec(normalizedKey, "AES");
this.transformation = transformation; // "AES/ECB/PKCS5Padding"
}
public String encrypt(String plaintext) throws Exception {
Cipher cipher = Cipher.getInstance(transformation);
cipher.init(Cipher.ENCRYPT_MODE, keySpec);
byte[] encrypted = cipher.doFinal(plaintext.getBytes(StandardCharsets.UTF_8));
return Base64.getEncoder().encodeToString(encrypted);
}
public String decrypt(String base64Ciphertext) throws Exception {
Cipher cipher = Cipher.getInstance(transformation);
cipher.init(Cipher.DECRYPT_MODE, keySpec);
byte[] decoded = Base64.getDecoder().decode(base64Ciphertext);
byte[] decrypted = cipher.doFinal(decoded);
return new String(decrypted, StandardCharsets.UTF_8);
}
// 測試主程式
public static void main(String[] args) throws Exception {
String key = "1234567891234567";
String data = "example";
AesCrypt aes = new AesCrypt(key, "AES/ECB/PKCS5Padding");
String encrypted = aes.encrypt(data);
String decrypted = aes.decrypt(encrypted);
System.out.println("Java Encrypt: " + encrypted);
System.out.println("Java Decrypt: " + decrypted);
// 應與 PHP 輸出完全一致
}
}
<?php
// PHP CBC
$aesCbc = new AesCrypt($key, 'AES-128-CBC');
$iv = random_bytes(16); // 每次加密生成隨機 IV
$encrypted = $aesCbc->encryptCbc($data, $iv);
// 傳輸格式:IV + 密文 (Base64 各自編碼或拼接)
$package = base64_encode($iv) . ':' . $encrypted;
// Java CBC
// String[] parts = package.split(":");
// byte[] iv = Base64.getDecoder().decode(parts[0]);
// String decrypted = aesCbc.decrypt(parts[1], iv);
<?php
// test_interop.php
$testCases = [
['key' => '1234567891234567', 'data' => 'example', 'method' => 'AES-128-ECB'],
['key' => '1234567891234567', 'data' => '中文測試測試', 'method' => 'AES-128-ECB'],
['key' => '12345678912345678912345678912345', 'data' => 'long key test', 'method' => 'AES-256-ECB'],
['key' => 'short', 'data' => 'short key padded', 'method' => 'AES-128-EBC'], // key 會補零
];
foreach ($testCases as $tc) {
$aes = new AesCrypt($tc['key'], $tc['method']);
$enc = $aes->encrypt($tc['data']);
$dec = $aes->decrypt($enc);
echo "Method: {$tc['method']} | KeyLen: " . strlen($tc['key']) . " | Data: {$tc['data']}\n";
echo "Enc: $enc\nDec: $dec\nMatch: " . ($dec === $tc['data'] ? 'YES' : 'NO') . "\n\n";
}
| 現象 | 可能原因 | 排查步驟 |
|---|---|---|
| 解密報錯 BadPaddingException | 填充不一致 / Key 長度不同 / 資料損壞 | 檢查 Key 正規化邏輯、確認 PKCS7/PKCS5、Base64 編碼完整 |
| 解密出亂碼 | 字元編碼不一致 (UTF-8 vs GBK/ISO-8859-1) | 雙方強制指定 UTF-8,檢查資料庫/檔案編碼 |
| 密文長度不同 | IV 處理不同 / 是否輸出 IV / Base64 換行 | 確認 IV 來源、Base64 無換行、ECB 不需 IV |
| PHP openssl_encrypt 返回 false | Key/IV 長度錯誤、方法名拼寫 | 檢查 openssl_error_string()、openssl_get_cipher_methods() |
<?php
// XChaCha20-Poly1305 (認證加密,無需手動管理 IV/Nonce 複雜度)
$key = sodium_crypto_aead_xchacha20poly1305_ietf_keygen();
$nonce = random_bytes(SODIUM_CRYPTO_AEAD_XCHACHA20POLY1305_IETF_NPUBBYTES);
$ciphertext = sodium_crypto_aead_xchacha20poly1305_ietf_encrypt(
'message', '', $nonce, $key
);
// 解密
$plaintext = sodium_crypto_aead_xchacha20poly1305_ietf_decrypt(
$ciphertext, '', $nonce, $key
);
// 優點:現代、安全、抗旁路攻擊、API 簡單、跨語言支援好 (libsodium 多語言綁定)
PHP-Java 加密互通關鍵在於Key 正規化邏輯對齊、填充模式一致、編碼統一。建議:
openssl 或 libsodium