2026年12月4日 星期五

128 位 AES 加密演算法(AES-128)

128 位 AES 加密演算法(AES-128)

 128 位 AES 加密演算法(AES-128)是一種對稱式區塊加密技術,使用 128 位元(16 位元組) 金鑰處理固定 128 位元(16 位元組) 的資料區塊,共執行 10 輪 轉換。 [1, 2, 3]

核心規格
  • 加密方式:對稱式加密,加密與解密使用同一把金鑰。
  • 金鑰長度:128 位元(16 bytes),共產生 10 輪加密所需的輪金鑰。
  • 區塊大小:128 位元(16 bytes),通常排列為 4×4 的位元組矩陣。
  • 加密輪數:10 輪(相較於 AES-192 的 12 輪與 AES-256 的 14 輪,運算速度最快)。 [1, 2, 3, 4, 5]
加密運作流程
  1. 金鑰擴充:由原始 128 位元金鑰推導出各輪使用的輪金鑰。 [1]
  2. 初始輪:將明文區塊與初始金鑰進行互斥或(XOR)運算。 [1]
  3. 前 9 輪標準轉換:每輪包含四個步驟:
    • SubBytes(位元組替代):透過 S-box 替換位元組。
    • ShiftRows(列位移):將矩陣各列進行循環位移。
    • MixColumns(行混合):對矩陣各行進行線性混合運算。
    • AddRoundKey(輪金鑰加):將狀態矩陣與當輪金鑰做 XOR。 [1, 2, 3]
  4. 第 10 輪(最終輪):執行 SubBytes、ShiftRows 與 AddRoundKey(省略 MixColumns)。 [1]
安全性與應用
  • 安全性:由美國 NIST 於 2001 年發布(FIPS PUB 197)。目前尚無實際可行的直接破解方法,暴力破解需面對 2¹²⁸ 種可能金鑰;實務上需防範金鑰外洩、弱金鑰及側信道攻擊(如功耗或時序分析)。
  • 常見用途:廣泛用於無線網路、傳輸加密、雲端儲存、資料庫與行動裝置或儲存硬體,在效能與安全之間取得良好平衡。
開發與安全重點
項目建議作法原因
Salt(鹽值)每次加密重新隨機產生(至少 16 bytes),明文附在密文前一起儲存防止彩虹表攻擊,確保相同密碼每次衍生出不同金鑰
迭代與記憶體參數PBKDF2-SHA256 設 60 萬次以上;Argon2id 設 64 MB 記憶體以上刻意拖慢運算速度,大幅提高暴力破解成本
加密模式務必搭配 GCM 認證加密若使用者輸入錯誤密碼,GCM 解密時會直接驗證失敗並報錯,不會吐出亂碼


import os

import base64

import tkinter as tk

from tkinter import messagebox

from cryptography.hazmat.primitives.kdf.argon2 import Argon2id

from cryptography.hazmat.primitives.ciphers.aead import AESGCM

from cryptography.exceptions import InvalidTag



def derive_key_argon2(password: str, salt: bytes) -> bytes:

    """使用 Argon2id 從密碼衍生 128 位元 (16 bytes) 金鑰"""

    kdf = Argon2id(

        salt=salt,

        length=16,          # 16 bytes = 128 bits

        iterations=2,       # 時間成本

        lanes=4,            # 平行度

        memory_cost=65536,  # 記憶體成本 64 MB

    )

    return kdf.derive(password.encode("utf-8"))



class AESArgon2App:

    def __init__(self, root: tk.Tk):

        self.root = root

        self.root.title("AES-128-GCM + Argon2id 加解密工具")

        self.root.geometry("600x570")

        self.root.resizable(False, False)


        self._build_ui()


    def _build_ui(self):

        pad_x = 20


        # 1. 密碼輸入區

        tk.Label(self.root, text="密碼 (Password):", font=("微軟正黑體", 10, "bold")).pack(

            anchor="w", padx=pad_x, pady=(15, 2)

        )

        pwd_frame = tk.Frame(self.root)

        pwd_frame.pack(fill="x", padx=pad_x)


        self.pwd_entry = tk.Entry(pwd_frame, show="*", font=("Consolas", 11))

        self.pwd_entry.pack(side="left", fill="x", expand=True)


        self.show_pwd_var = tk.BooleanVar(value=False)

        tk.Checkbutton(

            pwd_frame,

            text="顯示密碼",

            variable=self.show_pwd_var,

            command=self.toggle_password,

        ).pack(side="right", padx=(8, 0))


        # 2. 明文輸入區

        tk.Label(self.root, text="輸入明文:", font=("微軟正黑體", 10, "bold")).pack(

            anchor="w", padx=pad_x, pady=(12, 2)

        )

        self.plain_text = tk.Text(self.root, height=4, font=("微軟正黑體", 10))

        self.plain_text.pack(fill="x", padx=pad_x)


        # 3. 操作按鈕區

        btn_frame = tk.Frame(self.root)

        btn_frame.pack(pady=12)


        tk.Button(

            btn_frame,

            text="🔒 執行加密",

            width=14,

            bg="#2b579a",

            fg="white",

            font=("微軟正黑體", 10, "bold"),

            command=self.encrypt_action,

        ).pack(side="left", padx=8)


        tk.Button(

            btn_frame,

            text="🔓 執行解密",

            width=14,

            bg="#217346",

            fg="white",

            font=("微軟正黑體", 10, "bold"),

            command=self.decrypt_action,

        ).pack(side="left", padx=8)


        tk.Button(

            btn_frame,

            text="清空全部",

            width=10,

            font=("微軟正黑體", 10),

            command=self.clear_all,

        ).pack(side="left", padx=8)


        # 4. 加密後資料顯示區 + 一鍵複製按鈕

        cipher_header = tk.Frame(self.root)

        cipher_header.pack(fill="x", padx=pad_x, pady=(4, 2))


        tk.Label(

            cipher_header,

            text="加密後資料 (Base64 格式):",

            font=("微軟正黑體", 10, "bold"),

        ).pack(side="left")


        self.copy_cipher_btn = tk.Button(

            cipher_header,

            text="📋 複製密文",

            font=("微軟正黑體", 9),

            padx=8,

            command=lambda: self.copy_to_clipboard(self.cipher_text, self.copy_cipher_btn, "📋 複製密文"),

        )

        self.copy_cipher_btn.pack(side="right")


        self.cipher_text = tk.Text(self.root, height=5, font=("Consolas", 9), bg="#f4f4f4")

        self.cipher_text.pack(fill="x", padx=pad_x)


        # 5. 解密後明文顯示區 + 一鍵複製按鈕

        dec_header = tk.Frame(self.root)

        dec_header.pack(fill="x", padx=pad_x, pady=(12, 2))


        tk.Label(

            dec_header,

            text="解密後明文:",

            font=("微軟正黑體", 10, "bold"),

        ).pack(side="left")


        self.copy_dec_btn = tk.Button(

            dec_header,

            text="📋 複製明文",

            font=("微軟正黑體", 9),

            padx=8,

            command=lambda: self.copy_to_clipboard(self.decrypted_text, self.copy_dec_btn, "📋 複製明文"),

        )

        self.copy_dec_btn.pack(side="right")


        self.decrypted_text = tk.Text(self.root, height=4, font=("微軟正黑體", 10), bg="#eef7ee")

        self.decrypted_text.pack(fill="x", padx=pad_x)


    def toggle_password(self):

        self.pwd_entry.config(show="" if self.show_pwd_var.get() else "*")


    def copy_to_clipboard(self, text_widget: tk.Text, button: tk.Button, default_label: str):

        """將指定文字框內容複製到系統剪貼簿,並提供按鈕狀態回饋"""

        content = text_widget.get("1.0", "end-1c").strip()

        if not content:

            messagebox.showinfo("提示", "目前欄位沒有可複製的內容!")

            return


        self.root.clipboard_clear()

        self.root.clipboard_append(content)

        self.root.update()  # 確保程式關閉或切換視窗後剪貼簿內容仍保留


        # 按鈕視覺回饋,1.5 秒後恢復原文字

        button.config(text="✔ 已複製", fg="#217346")

        self.root.after(1500, lambda: button.config(text=default_label, fg="black"))


    def encrypt_action(self):

        password = self.pwd_entry.get()

        plaintext = self.plain_text.get("1.0", "end-1c")


        if not password:

            messagebox.showwarning("提示", "請先輸入密碼!")

            return

        if not plaintext:

            messagebox.showwarning("提示", "請輸入要加密的明文!")

            return


        try:

            salt = os.urandom(16)

            nonce = os.urandom(12)

            key = derive_key_argon2(password, salt)

            ciphertext = AESGCM(key).encrypt(nonce, plaintext.encode("utf-8"), None)


            payload_b64 = base64.b64encode(salt + nonce + ciphertext).decode("utf-8")


            self.cipher_text.delete("1.0", tk.END)

            self.cipher_text.insert("1.0", payload_b64)

            self.decrypted_text.delete("1.0", tk.END)

        except Exception as e:

            messagebox.showerror("加密錯誤", f"發生未預期錯誤:{e}")


    def decrypt_action(self):

        password = self.pwd_entry.get()

        payload_b64 = self.cipher_text.get("1.0", "end-1c").strip()


        if not password:

            messagebox.showwarning("提示", "請先輸入解密密碼!")

            return

        if not payload_b64:

            messagebox.showwarning("提示", "請在「加密後資料」欄位中填入要解密的內容!")

            return


        try:

            raw = base64.b64decode(payload_b64)

            if len(raw) < 28:

                raise ValueError("密文長度不足,格式不正確")


            salt = raw[:16]

            nonce = raw[16:28]

            ciphertext = raw[28:]


            key = derive_key_argon2(password, salt)

            decrypted_bytes = AESGCM(key).decrypt(nonce, ciphertext, None)


            self.decrypted_text.delete("1.0", tk.END)

            self.decrypted_text.insert("1.0", decrypted_bytes.decode("utf-8"))

        except InvalidTag:

            messagebox.showerror("解密失敗", "密碼錯誤,或密文資料已遭竄改!")

        except Exception as e:

            messagebox.showerror("解密失敗", f"無法解析密文格式:{e}")


    def clear_all(self):

        self.pwd_entry.delete(0, tk.END)

        self.plain_text.delete("1.0", tk.END)

        self.cipher_text.delete("1.0", tk.END)

        self.decrypted_text.delete("1.0", tk.END)



if __name__ == "__main__":

    root = tk.Tk()

    app = AESArgon2App(root)

    root.mainloop()

程式功能亮點

  • 完整封裝結構:加密結果會將隨機產生的 Salt (16 bytes)、Nonce (12 bytes) 與密文串接後轉為 Base64,方便在視窗中複製、貼上或測試獨立解密。
  • 防呆與竄改偵測:解密時若密碼輸入錯誤或密文少了一個字元,會觸發 InvalidTag 例外並跳出明確的錯誤提示,不會顯示亂碼。

無法從ㄧ串密文回推原始密碼。
這串 Base64 資料解碼後共有 62 個位元組,完全符合前面程式的封裝結構:
  • 前 16 bytes(Salt):db57ac01b8663e13c2643825acdf19e5(隨機鹽值)
  • 中間 12 bytes(Nonce):23cc5489ea84127eea0d55ac3641aef7(隨機初始向量)
  • 最後 34 bytes(密文 + Auth Tag):包含 18 bytes 的加密後明文與 16 bytes 的 GCM 完整性驗證標籤。
為什麼無法回推?
  1. 單向雜湊不可逆:程式使用的 Argon2id 屬於密碼學單向衍生函數(KDF),設計上只能從「密碼 + Salt」單向計算出金鑰,沒有任何數學公式能從密文或金鑰反推出原始密碼。
  2. 記憶體與時間成本極高:即使採取暴力猜測(字典攻擊),每次嘗試一個密碼都必須重新跑一次 64 MB 記憶體與多輪運算的 Argon2id,再加上隨機 Salt 阻斷了預先計算(彩虹表)的可能;只要原始密碼具備足夠長度與複雜度(例如 12 字元以上含大小寫、數字與符號),在實務上幾乎不可能被暴力破解。

沒有留言:

張貼留言

128 位 AES 加密演算法(AES-128)

128 位 AES 加密演算法(AES-128)   128 位 AES 加密演算法(AES-128) 是一種對稱式區塊加密技術,使用 128 位元(16 位元組) 金鑰處理固定 128 位元(16 位元組) 的資料區塊,共執行 10 輪 轉換 。 [ 1 , 2 , 3...