AES(Advanced Encryption Standard,進階加密標準) 原名 Rijndael,由比利時密碼學家 Joan Daemen 與 Vincent Rijmen 設計,並於 2001 年獲美國 NIST 正式採納為官方標準,用以全面取代安全性不足且效率低落的 DES 與 3DES。
作為當今全球資安領域應用最廣、極度可靠的對稱式區塊加密演算法,AES 被廣泛應用於 TLS 1.3、Wi-Fi WPA3、Signal 隱私通訊、BitLocker 磁碟加密以及各國政府與金融體系的資料保密防線中。
與 DES/3DES 所採用的 Feistel 網路結構不同,AES 採用了 代換置換網路(Substitution-Permutation Network, SPN) 架構。在 SPN 中,每一輪運算都會同時對整個 128-bit 區塊的所有位元進行並行處理,而非像DES演算法僅處理一半的區塊。
| 參數項目 | AES-128 | AES-192 | AES-256 |
|---|---|---|---|
| 區塊大小 (Block Size) | 128 bits (16 Bytes) | 128 bits (16 Bytes) | 128 bits (16 Bytes) |
| 金鑰長度 (Key Length) | 128 bits (16 Bytes) | 192 bits (24 Bytes) | 256 bits (32 Bytes) |
| 迭代輪數 (Rounds) | 10 輪 | 12 輪 | 14 輪 |
| 子金鑰數量與長度 | 11 組 128-bit 子金鑰 | 13 組 128-bit 子金鑰 | 15 組 128-bit 子金鑰 |
| 安全強度 | 抵禦當前所有已知攻擊 | 高安全性需求的標準 | 抗量子演算預期標準 |
註:AES 將 128-bit(16 位元組)的資料區塊表示為一個 4 X 4 的矩陣,稱為 狀態矩陣(State Matrix)。

在 Java 中,推薦使用 AES/GCM/NoPadding(具有認證防篡改功能的 AEAD 模式)作為對稱加密的首選方案。以下提供包含完整加密與解密的程式碼範例:
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.GCMParameterSpec;
import java.nio.charset.StandardCharsets;
import java.security.SecureRandom;
import java.util.Base64;
public class AESGCMExample {
private static final int AES_KEY_SIZE = 256; // 首選 256 bits 安全強度
private static final int GCM_IV_LENGTH = 12; // GCM 模式標準 IV (Nonce) 長度為 12 位元組
private static final int GCM_TAG_LENGTH = 128; // 認證標籤長度 128 bits
public static void main(String[] args) throws Exception {
String originalText = "Hello, Modern Cryptography!";
// ==================== 1. 金鑰與 IV 生成 ====================
// 生成 AES-256 秘密金鑰
KeyGenerator keyGen = KeyGenerator.getInstance("AES");
keyGen.init(AES_KEY_SIZE);
SecretKey key = keyGen.generateKey();
// 生成強隨機 IV (Nonce)
byte[] iv = new byte[GCM_IV_LENGTH];
new SecureRandom().nextBytes(iv);
// ==================== 2. 加密流程 (Encryption) ====================
Cipher cipherEncrypt = Cipher.getInstance("AES/GCM/NoPadding");
GCMParameterSpec spec = new GCMParameterSpec(GCM_TAG_LENGTH, iv);
cipherEncrypt.init(Cipher.ENCRYPT_MODE, key, spec);
byte[] ciphertext = cipherEncrypt.doFinal(originalText.getBytes(StandardCharsets.UTF_8));
System.out.println("加密結果 (Base64): " + Base64.getEncoder().encodeToString(ciphertext));
// ==================== 3. 解密流程 (Decryption) ====================
Cipher cipherDecrypt = Cipher.getInstance("AES/GCM/NoPadding");
// 解密時必須使用與加密時相同的金鑰、IV 以及 Tag 長度規格
cipherDecrypt.init(Cipher.DECRYPT_MODE, key, spec);
// doFinal 會自動進行 1. 密文解密 2. GCM Auth Tag 認證標籤驗證
byte[] decryptedBytes = cipherDecrypt.doFinal(ciphertext);
String decryptedText = new String(decryptedBytes, StandardCharsets.UTF_8);
System.out.println("解密後的原文: " + decryptedText);
}
}
doFinal() 進行解密時,JCA 會自動校驗密文末尾的 128-bit Auth Tag。doFinal() 時會自動拋出 javax.crypto.AEADBadTagException 異常並拒絕解密,徹底防止資料被篡改(Integrity Protection)。IV || Ciphertext)一同傳送給接收方,解密前再由前 12 位元組拆解出 IV。