萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP 與 Java AES/DES 加密互通實戰:跨語言加解密完整對齊指南

核心問題:為什麼 PHP 與 Java 加密結果不一致?

同樣是 AES-128-ECB-PKCS5Padding,PHP mcrypt/openssl 與 Java Cipher 經常產生不同密文,主因在於:

  1. Key 處理差異:PHP 直接用字串,Java SecretKeySpec 用 byte[],編碼/截斷/補零邏輯不同
  2. IV 處理:ECB 模式不需 IV,但 PHP mcrypt 要求提供、Java 忽略
  3. 填充模式:PHP mcrypt 需手動 PKCS7,Java 內建 PKCS5Padding
  4. Base64 編碼:雙方編碼/解碼時機是否一致

統一規範 (Interop Spec)

參數規範值說明
演算法AES-128-ECB或 AES-256-CBC (需 IV)
Key16/32 bytes UTF-8 bytes不足補 \0,超過截斷
填充PKCS#7 (PKCS5Padding)Java 標準名,PHP 需手動實現
輸出編碼Base64 (標準 RFC4648)無換行、無空格
字元編碼UTF-8明文/密文轉 bytes 統一用 UTF-8

PHP 實現 (OpenSSL 推薦,mcrypt 已棄用)

<?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 端一致

Java 實現 (對齊 PHP)

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 輸出完全一致
    }
}

CBC 模式互通 (需 IV)

<?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 返回 falseKey/IV 長度錯誤、方法名拼寫檢查 openssl_error_string()、openssl_get_cipher_methods()

現代替代方案:libsodium (PHP 7.2+ 內建)

<?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 正規化邏輯對齊、填充模式一致、編碼統一。建議:

  1. 棄用 mcrypt,全面遷移至 openssl 或 libsodium
  2. 制定跨語言加密規範文檔 (Key長度、填充、編碼、IV管理)
  3. 雙方編寫單元測試互相驗證
  4. 新專案優先考慮 libsodium/XChaCha20-Poly1305 避免模式選擇困擾
copyright © 萬盛學電腦網 all rights reserved