2026年11月19日 星期四

使用 Python + Tkinter + SQLite 製作的「簡易通訊錄」桌面應用程式

使用 Python + Tkinter + SQLite 製作的「簡易通訊錄」桌面應用程式

這個版本不需要額外安裝任何第三方套件(皆為 Python 內建標準函式庫),資料會自動儲存在本地的 contacts.db 資料庫中,並支援新增、修改、刪除、關鍵字搜尋以及匯出 CSV 功能。

完整程式碼 (address_book.py)

Python
import csv
import sqlite3
import tkinter as tk
from tkinter import filedialog, messagebox, ttk


class AddressBookApp:

    def __init__(self, root):
        self.root = root
        self.root.title("簡易通訊錄管理系統")
        self.root.geometry("780x520")
        self.root.resizable(True, True)

        # 初始化資料庫
        self.db_name = "contacts.db"
        self.init_db()

        # 當前選取的資料 ID
        self.selected_id = None

        # 建立介面
        self.setup_ui()
        self.load_data()

    def init_db(self):
        """建立 SQLite 資料表"""
        with sqlite3.connect(self.db_name) as conn:
            cursor = conn.cursor()
            cursor.execute("""
                CREATE TABLE IF NOT EXISTS contacts (
                    id INTEGER PRIMARY KEY AUTOINCREMENT,
                    name TEXT NOT NULL,
                    phone TEXT NOT NULL,
                    email TEXT,
                    group_name TEXT,
                    note TEXT
                )
            """)
            conn.commit()

    def setup_ui(self):
        """建立畫面元件"""
        # --- 上方:輸入表單區 ---
        form_frame = ttk.LabelFrame(
            self.root, text="聯絡人資料", padding=(10, 10)
        )
        form_frame.pack(fill="x", padx=10, pady=5)

        # 第一列:姓名、電話、群組
        ttk.Label(form_frame, text="姓名 *:").grid(
            row=0, column=0, sticky="e", pady=5
        )
        self.name_var = tk.StringVar()
        ttk.Entry(form_frame, textvariable=self.name_var, width=18).grid(
            row=0, column=1, padx=5, pady=5
        )

        ttk.Label(form_frame, text="電話 *:").grid(
            row=0, column=2, sticky="e", pady=5
        )
        self.phone_var = tk.StringVar()
        ttk.Entry(form_frame, textvariable=self.phone_var, width=18).grid(
            row=0, column=3, padx=5, pady=5
        )

        ttk.Label(form_frame, text="群組:").grid(
            row=0, column=4, sticky="e", pady=5
        )
        self.group_var = tk.StringVar(value="一般")
        group_combo = ttk.Combobox(
            form_frame,
            textvariable=self.group_var,
            values=["一般", "家人", "朋友", "同事", "廠商", "山友"],
            width=15,
        )
        group_combo.grid(row=0, column=5, padx=5, pady=5)

        # 第二列:Email、備註
        ttk.Label(form_frame, text="Email:").grid(
            row=1, column=0, sticky="e", pady=5
        )
        self.email_var = tk.StringVar()
        ttk.Entry(form_frame, textvariable=self.email_var, width=18).grid(
            row=1, column=1, padx=5, pady=5
        )

        ttk.Label(form_frame, text="備註:").grid(
            row=1, column=2, sticky="e", pady=5
        )
        self.note_var = tk.StringVar()
        ttk.Entry(form_frame, textvariable=self.note_var, width=44).grid(
            row=1, column=3, columnspan=3, sticky="w", padx=5, pady=5
        )

        # --- 中間:操作按鈕與搜尋區 ---
        btn_frame = ttk.Frame(self.root, padding=(10, 5))
        btn_frame.pack(fill="x")

        ttk.Button(btn_frame, text="新增", command=self.add_contact, width=8).pack(
            side="left", padx=3
        )
        ttk.Button(
            btn_frame, text="修改", command=self.update_contact, width=8
        ).pack(side="left", padx=3)
        ttk.Button(
            btn_frame, text="刪除", command=self.delete_contact, width=8
        ).pack(side="left", padx=3)
        ttk.Button(
            btn_frame, text="清空欄位", command=self.clear_fields, width=10
        ).pack(side="left", padx=3)
        ttk.Button(
            btn_frame, text="匯出 CSV", command=self.export_csv, width=10
        ).pack(side="left", padx=3)

        # 搜尋框(靠右對齊)
        ttk.Button(btn_frame, text="顯示全部", command=self.load_data).pack(
            side="right", padx=3
        )
        ttk.Button(btn_frame, text="搜尋", command=self.search_contact).pack(
            side="right", padx=3
        )
        self.search_var = tk.StringVar()
        search_entry = ttk.Entry(
            btn_frame, textvariable=self.search_var, width=18
        )
        search_entry.pack(side="right", padx=3)
        search_entry.bind("<Return>", lambda event: self.search_contact())
        ttk.Label(btn_frame, text="關鍵字:").pack(side="right")

        # --- 下方:資料列表區 (Treeview) ---
        table_frame = ttk.Frame(self.root, padding=(10, 5))
        table_frame.pack(fill="both", expand=True)

        columns = ("id", "name", "phone", "group", "email", "note")
        self.tree = ttk.Treeview(
            table_frame, columns=columns, show="headings", selectmode="browse"
        )

        # 設定欄位標題與寬度
        self.tree.heading("id", text="編號")
        self.tree.heading("name", text="姓名")
        self.tree.heading("phone", text="電話")
        self.tree.heading("group", text="群組")
        self.tree.heading("email", text="Email")
        self.tree.heading("note", text="備註")

        self.tree.column("id", width=50, anchor="center")
        self.tree.column("name", width=100, anchor="center")
        self.tree.column("phone", width=120, anchor="center")
        self.tree.column("group", width=80, anchor="center")
        self.tree.column("email", width=180, anchor="w")
        self.tree.column("note", width=200, anchor="w")

        # 捲動軸
        scrollbar = ttk.Scrollbar(
            table_frame, orient="vertical", command=self.tree.yview
        )
        self.tree.configure(yscrollcommand=scrollbar.set)

        self.tree.pack(side="left", fill="both", expand=True)
        scrollbar.pack(side="right", fill="y")

        # 綁定點擊事件
        self.tree.bind("<<TreeviewSelect>>", self.on_tree_select)

    def load_data(self, query=None, params=()):
        """載入資料至表格"""
        for row in self.tree.get_children():
            self.tree.delete(row)

        with sqlite3.connect(self.db_name) as conn:
            cursor = conn.cursor()
            if query:
                cursor.execute(query, params)
            else:
                cursor.execute(
                    "SELECT id, name, phone, group_name, email, note FROM contacts ORDER BY id DESC"
                )
            for row in cursor.fetchall():
                self.tree.insert("", "end", values=row)

    def add_contact(self):
        """新增聯絡人"""
        name = self.name_var.get().strip()
        phone = self.phone_var.get().strip()
        if not name or not phone:
            messagebox.showwarning("欄位缺漏", "「姓名」與「電話」為必填欄位!")
            return

        with sqlite3.connect(self.db_name) as conn:
            cursor = conn.cursor()
            cursor.execute(
                "INSERT INTO contacts (name, phone, email, group_name, note) VALUES (?, ?, ?, ?, ?)",
                (
                    name,
                    phone,
                    self.email_var.get().strip(),
                    self.group_var.get().strip(),
                    self.note_var.get().strip(),
                ),
            )
            conn.commit()

        self.clear_fields()
        self.load_data()
        messagebox.showinfo("成功", f"已新增聯絡人:{name}")

    def update_contact(self):
        """修改選取的聯絡人"""
        if not self.selected_id:
            messagebox.showwarning("未選取", "請先從下方列表點選要修改的聯絡人!")
            return

        name = self.name_var.get().strip()
        phone = self.phone_var.get().strip()
        if not name or not phone:
            messagebox.showwarning("欄位缺漏", "「姓名」與「電話」為必填欄位!")
            return

        with sqlite3.connect(self.db_name) as conn:
            cursor = conn.cursor()
            cursor.execute(
                """UPDATE contacts 
                   SET name=?, phone=?, email=?, group_name=?, note=? 
                   WHERE id=?""",
                (
                    name,
                    phone,
                    self.email_var.get().strip(),
                    self.group_var.get().strip(),
                    self.note_var.get().strip(),
                    self.selected_id,
                ),
            )
            conn.commit()

        self.clear_fields()
        self.load_data()
        messagebox.showinfo("成功", "資料已更新!")

    def delete_contact(self):
        """刪除選取的聯絡人"""
        if not self.selected_id:
            messagebox.showwarning("未選取", "請先從下方列表點選要刪除的聯絡人!")
            return

        if messagebox.askyesno(
            "確認刪除", f"確定要刪除「{self.name_var.get()}」的資料嗎?"
        ):
            with sqlite3.connect(self.db_name) as conn:
                cursor = conn.cursor()
                cursor.execute(
                    "DELETE FROM contacts WHERE id=?", (self.selected_id,)
                )
                conn.commit()
            self.clear_fields()
            self.load_data()

    def search_contact(self):
        """關鍵字搜尋(支援姓名、電話、群組、備註)"""
        keyword = f"%{self.search_var.get().strip()}%"
        query = """
            SELECT id, name, phone, group_name, email, note 
            FROM contacts 
            WHERE name LIKE ? OR phone LIKE ? OR group_name LIKE ? OR note LIKE ?
            ORDER BY id DESC
        """
        self.load_data(query, (keyword, keyword, keyword, keyword))

    def on_tree_select(self, event):
        """點選列表項目時,將資料帶入上方輸入框"""
        selected = self.tree.selection()
        if selected:
            values = self.tree.item(selected[0], "values")
            self.selected_id = values[0]
            self.name_var.set(values[1])
            self.phone_var.set(values[2])
            self.group_var.set(values[3])
            self.email_var.set(values[4])
            self.note_var.set(values[5])

    def clear_fields(self):
        """清空輸入欄位"""
        self.selected_id = None
        self.name_var.set("")
        self.phone_var.set("")
        self.group_var.set("一般")
        self.email_var.set("")
        self.note_var.set("")
        if self.tree.selection():
            self.tree.selection_remove(self.tree.selection())

    def export_csv(self):
        """匯出成 Excel 可開啟的 UTF-8-SIG CSV 檔"""
        file_path = filedialog.asksaveasfilename(
            defaultextension=".csv",
            filetypes=[("CSV 檔案", "*.csv")],
            initialfile="通訊錄備份.csv",
        )
        if not file_path:
            return

        with sqlite3.connect(self.db_name) as conn:
            cursor = conn.cursor()
            cursor.execute(
                "SELECT id, name, phone, group_name, email, note FROM contacts"
            )
            rows = cursor.fetchall()

        with open(file_path, "w", newline="", encoding="utf-8-sig") as f:
            writer = csv.writer(f)
            writer.writerow(["編號", "姓名", "電話", "群組", "Email", "備註"])
            writer.writerows(rows)

        messagebox.showinfo("匯出完成", f"已成功匯出 {len(rows)} 筆資料!")


if __name__ == "__main__":
    root = tk.Tk()
    app = AddressBookApp(root)
    root.mainloop()

功能亮點

  1. 即時資料庫儲存:所有資料直接寫入同目錄下的 contacts.db(SQLite),重開程式資料不會遺失。

  2. 一鍵點選編輯:在下方表格點選任一聯絡人,資料會自動帶入上方表單,方便直接修改或刪除。

  3. 支援 Excel 匯出:匯出 CSV 時已採用 utf-8-sig 編碼,用 Windows 的 Excel 直接雙擊開啟不會出現中文亂碼。

2026年11月16日 星期一

MIFARE DESFire對稱式加密演算法

 MIFARE DESFire對稱式加密演算法


MIFARE DESFire 採用的是雙向挑戰-回應認證機制(Mutual Challenge-Response Authentication),並支援 3DES 與 AES-128 對稱式加密演算法。透過 Python 搭配標準圖形介面庫 Tkinter 以及加密套件 cryptography,可以完整模擬並視覺化展示讀卡機(Reader)與卡片(Card)之間如何驗證彼此身分並產生動態「會話金鑰(Session Key)」的過程。
1. MIFARE DESFire 加密認證核心流程
在進行任何資料讀寫前,讀卡機與 DESFire 卡片必須完成以下三階段的隨機數交換與加密驗證(以 AES-128 為例):
  • 階段一(卡片發起挑戰)。 讀卡機發送認證指令後,卡片產生一組 16 位元組的隨機數 RndB,並使用雙方共享的主金鑰(Master Key)將其加密後傳送給讀卡機。
  • 階段二(讀卡機回應與反向挑戰)。 讀卡機解密取得 RndB,將其向左循環位移 1 個位元組得到 RndB',同時自行產生另一組隨機數 RndA。接著讀卡機將 RndA + RndB' 串接並加密,回傳給卡片。
  • 階段三(卡片驗證與會話金鑰生成)。 卡片解密後比對 RndB' 是否正確,確認讀卡機擁有合法金鑰。接著卡片將 RndA 向左位移 1 個位元組得到 RndA',加密後回傳給讀卡機驗證;雙方最後混合 RndA 與 RndB 的特定位元組,組合成該次連線專用的 Session Key。


2. Python + Tkinter 互動模擬程式
import os
import tkinter as tk
from tkinter import ttk, scrolledtext
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes

class DESFireSimulatorApp:
    def __init__(self, root):
        self.root = root
        self.root.title("MIFARE DESFire AES-128 雙向認證模擬器")
        self.root.geometry("720x560")
        self.root.configure(padx=15, pady=15)

        # 預設 16-byte (128-bit) 共享主金鑰
        self.master_key = bytes.fromhex("00112233445566778899AABBCCDDEEFF")
        self.iv = b'\x00' * 16  # DESFire 認證初始向量為全 0

        self._setup_ui()

    def _setup_ui(self):
        # 標題與金鑰設定區
        top_frame = ttk.LabelFrame(self.root, text="系統參數設定", padding=10)
        top_frame.pack(fill="x", pady=(0, 10))

        ttk.Label(top_frame, text="共享主金鑰 (AES-128 Hex):").grid(row=0, column=0, sticky="w")
        self.key_var = tk.StringVar(value=self.master_key.hex().upper())
        key_entry = ttk.Entry(top_frame, textvariable=self.key_var, width=40, font=("Consolas", 10))
        key_entry.grid(row=0, column=1, padx=10)

        run_btn = ttk.Button(top_frame, text="執行雙向認證流程", command=self.run_authentication)
        run_btn.grid(row=0, column=2)

        # 步驟日誌顯示區
        log_frame = ttk.LabelFrame(self.root, text="認證封包與金鑰演算過程", padding=10)
        log_frame.pack(fill="both", expand=True)

        self.log_area = scrolledtext.ScrolledText(log_frame, font=("Consolas", 10), wrap=tk.WORD)
        self.log_area.pack(fill="both", expand=True)

        # 設定文字顏色標籤
        self.log_area.tag_config("step", foreground="#0052cc", font=("Consolas", 10, "bold"))
        self.log_area.tag_config("success", foreground="#008000", font=("Consolas", 10, "bold"))
        self.log_area.tag_config("error", foreground="#cc0000", font=("Consolas", 10, "bold"))

    def aes_encrypt(self, key: bytes, data: bytes) -> bytes:
        cipher = Cipher(algorithms.AES(key), modes.CBC(self.iv))
        encryptor = cipher.encryptor()
        return encryptor.update(data) + encryptor.finalize()

    def aes_decrypt(self, key: bytes, data: bytes) -> bytes:
        cipher = Cipher(algorithms.AES(key), modes.CBC(self.iv))
        decryptor = cipher.decryptor()
        return decryptor.update(data) + decryptor.finalize()

    def rotate_left(self, data: bytes) -> bytes:
        """向左循環位移 1 個位元組 (DESFire 標準操作)"""
        return data[1:] + data[:1]

    def log(self, text: str, tag: str = None):
        self.log_area.insert(tk.END, text + "\n", tag)
        self.log_area.see(tk.END)

    def run_authentication(self):
        self.log_area.delete(1.0, tk.END)
        try:
            key_hex = self.key_var.get().strip()
            key = bytes.fromhex(key_hex)
            if len(key) != 16:
                raise ValueError("AES-128 金鑰長度必須為 16 Bytes (32 個 Hex 字元)。")
        except Exception as e:
            self.log(f"[錯誤] 金鑰格式無效: {e}", "error")
            return

        self.log("=== 開始 MIFARE DESFire AES-128 雙向認證 ===\n", "step")

        # 1. 卡片產生 RndB 並加密傳送
        rnd_b = os.urandom(16)
        enc_rnd_b = self.aes_encrypt(key, rnd_b)
        self.log("[步驟 1] 卡片 (Card) 發起挑戰", "step")
        self.log(f"  卡片產生隨機數 RndB : {rnd_b.hex().upper()}")
        self.log(f"  卡片傳送 Enc(RndB)  : {enc_rnd_b.hex().upper()}\n")

        # 2. 讀卡機解密 RndB,產生 RndA,組合 RndA + RndB' 並加密
        dec_rnd_b = self.aes_decrypt(key, enc_rnd_b)
        rnd_b_rot = self.rotate_left(dec_rnd_b)
        rnd_a = os.urandom(16)
        token_ab = rnd_a + rnd_b_rot
        enc_token_ab = self.aes_encrypt(key, token_ab)

        self.log("[步驟 2] 讀卡機 (Reader) 回應並提出反向挑戰", "step")
        self.log(f"  讀卡機解密取得 RndB : {dec_rnd_b.hex().upper()}")
        self.log(f"  左移 1 Byte 變 RndB': {rnd_b_rot.hex().upper()}")
        self.log(f"  讀卡機產生隨機 RndA : {rnd_a.hex().upper()}")
        self.log(f"  傳送 Enc(RndA+RndB'): {enc_token_ab.hex().upper()}\n")

        # 3. 卡片解密並驗證 RndB',回傳 Enc(RndA')
        dec_token_ab = self.aes_decrypt(key, enc_token_ab)
        card_received_rnd_a = dec_token_ab[:16]
        card_received_rnd_b_rot = dec_token_ab[16:]

        self.log("[步驟 3] 卡片驗證讀卡機並回傳最終確認", "step")
        if card_received_rnd_b_rot == self.rotate_left(rnd_b):
            self.log("  -> 卡片驗證 RndB' 成功!確認讀卡機合法。", "success")
        else:
            self.log("  -> 卡片驗證失敗!終止連線。", "error")
            return

        rnd_a_rot = self.rotate_left(card_received_rnd_a)
        enc_rnd_a_rot = self.aes_encrypt(key, rnd_a_rot)
        self.log(f"  卡片傳送 Enc(RndA') : {enc_rnd_a_rot.hex().upper()}\n")

        # 4. 讀卡機驗證 RndA' 並產生 Session Key
        dec_rnd_a_rot = self.aes_decrypt(key, enc_rnd_a_rot)
        self.log("[步驟 4] 讀卡機驗證卡片並生成動態會話金鑰 (Session Key)", "step")
        if dec_rnd_a_rot == self.rotate_left(rnd_a):
            self.log("  -> 讀卡機驗證 RndA' 成功!雙向認證完成。", "success")
        else:
            self.log("  -> 讀卡機驗證失敗!", "error")
            return

        # DESFire AES Session Key 組合規則: RndA[0..3] + RndB[0..3] + RndA[12..15] + RndB[12..15]
        session_key = rnd_a[0:4] + rnd_b[0:4] + rnd_a[12:16] + rnd_b[12:16]
        self.log(f"\n[最終結果] 本次通訊專屬 Session Key (AES-128):", "success")
        self.log(f"  {session_key.hex().upper()}", "success")

if __name__ == "__main__":
    root = tk.Tk()
    app = DESFireSimulatorApp(root)
    root.mainloop()



3. 程式碼中的關鍵資安設計說明
透過上述模擬器的實作,可以看出 MIFARE DESFire 之所以難以被重放攻擊(Replay Attack)或側錄破解的三大設計:
  • 隨機數防重放(Nonce)。 每次感應都會產生全新的 RndA 與 RndB,因此即使攻擊者在無線電波中側錄到完整的加密封包,下一次通訊時因為隨機數已改變,舊封包將完全失效。
  • 循環位移防篡改(Bitwise Rotation)。 雙方在回傳對方的隨機數前,必須先執行 rotate_left(向左位移 1 個位元組),這確保了回應方確實具備「解密出明文、修改內容、再重新加密」的能力,而非單純將收到的密文原封不動反射回去。
  • 動態會話金鑰(Session Key)。 認證完成後,後續的檔案讀寫不再使用固定的主金鑰,而是改用由 RndA 與 RndB 頭尾各取 4 個位元組拼接而成的 Session Key,大幅降低主金鑰在長時間資料傳輸中被分析破解的風險。



在完成雙向認證並取得 Session Key(會話金鑰) 後,MIFARE DESFire 會進入安全通訊階段(Full Enciphered Communication)。為了確保資料在無線傳輸過程中不被竊聽(機密性)且不被竄改(完整性),系統會結合 CRC32 校驗碼 與 AES-CBC 區塊加密(或在 EV1/EV2 中搭配 CMAC)來封裝指令與資料。
1. 資料加密傳輸(Enciphered Mode)封裝流程
當讀卡機要寫入一筆機密資料(例如儲值金額或門禁權限)到卡片時,會依序執行以下處理:
  • 計算 CRC32 校驗碼。 將指令代碼(CMD)、檔案參數與原始明文資料組合,計算出 4 位元組的 CRC32(DESFire 標準採用反向多項式並進行位元反轉),附加在明文後方以防止傳輸過程中的資料損毀或竄改。
  • 零填充對齊(Zero Padding)。 由於 AES 區塊長度固定為 16 位元組(128 bits),若「明文 + CRC32」的總長度不足 16 的倍數,必須在後方補上 0x00 直到對齊區塊邊界。
  • AES-CBC 連鎖加密與 IV 更新。 使用認證階段產生的 Session Key 進行 AES-CBC 加密。在 DESFire 規範中,每次傳輸後都會保留最後一個密文區塊作為下一次通訊的初始向量(IV),讓前後封包產生密碼學連鎖,徹底阻斷重放或封包替換攻擊。

2. Python + Tkinter 完整加密傳輸模擬器
此程式延續先前的雙向認證,新增了輸入明文資料、自動計算 CRC32、執行 AES-CBC 加密傳輸,以及卡片端解密與完整性驗證的完整視覺化介面:
import os
import zlib
import tkinter as tk
from tkinter import ttk, scrolledtext
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes

class DESFireDataTransferApp:
    def __init__(self, root):
        self.root = root
        self.root.title("MIFARE DESFire 安全資料傳輸模擬器 (Session Key + CRC32 + AES-CBC)")
        self.root.geometry("760x640")
        self.root.configure(padx=15, pady=15)

        self.master_key = bytes.fromhex("00112233445566778899AABBCCDDEEFF")
        self.session_key = None
        self.current_iv = b'\x00' * 16  # 追蹤動態 IV 狀態

        self._setup_ui()

    def _setup_ui(self):
        # 1. 認證區塊
        auth_frame = ttk.LabelFrame(self.root, text="步驟 A:建立安全連線 (雙向認證)", padding=10)
        auth_frame.pack(fill="x", pady=(0, 10))

        ttk.Label(auth_frame, text="主金鑰 (AES-128):").grid(row=0, column=0, sticky="w")
        self.key_var = tk.StringVar(value=self.master_key.hex().upper())
        ttk.Entry(auth_frame, textvariable=self.key_var, width=36, font=("Consolas", 10)).grid(row=0, column=1, padx=8)

        ttk.Button(auth_frame, text="1. 執行認證並產生 Session Key", command=self.authenticate).grid(row=0, column=2)

        self.session_lbl = ttk.Label(auth_frame, text="目前 Session Key: 尚未認證", foreground="#cc0000", font=("Consolas", 9, "bold"))
        self.session_lbl.grid(row=1, column=0, columnspan=3, sticky="w", pady=(8, 0))

        # 2. 資料加密傳輸區塊
        data_frame = ttk.LabelFrame(self.root, text="步驟 B:安全寫入檔案 (WriteData - Enciphered Mode)", padding=10)
        data_frame.pack(fill="x", pady=(0, 10))

        ttk.Label(data_frame, text="寫入明文內容:").grid(row=0, column=0, sticky="w")
        self.data_var = tk.StringVar(value="BALANCE=5000_TWD")
        ttk.Entry(data_frame, textvariable=self.data_var, width=36, font=("Consolas", 10)).grid(row=0, column=1, padx=8)

        self.send_btn = ttk.Button(data_frame, text="2. 加密傳送並驗證", command=self.transfer_data, state="disabled")
        self.send_btn.grid(row=0, column=2)

        # 3. 封包與演算法日誌區
        log_frame = ttk.LabelFrame(self.root, text="無線射頻 (RF) 封包傳輸與加解密細節", padding=10)
        log_frame.pack(fill="both", expand=True)

        self.log_area = scrolledtext.ScrolledText(log_frame, font=("Consolas", 10), wrap=tk.WORD)
        self.log_area.pack(fill="both", expand=True)

        self.log_area.tag_config("title", foreground="#0052cc", font=("Consolas", 10, "bold"))
        self.log_area.tag_config("ok", foreground="#008000", font=("Consolas", 10, "bold"))
        self.log_area.tag_config("err", foreground="#cc0000", font=("Consolas", 10, "bold"))
        self.log_area.tag_config("hex", foreground="#444444")

    def aes_cbc_encrypt(self, key: bytes, iv: bytes, data: bytes) -> bytes:
        cipher = Cipher(algorithms.AES(key), modes.CBC(iv))
        enc = cipher.encryptor()
        return enc.update(data) + enc.finalize()

    def aes_cbc_decrypt(self, key: bytes, iv: bytes, data: bytes) -> bytes:
        cipher = Cipher(algorithms.AES(key), modes.CBC(iv))
        dec = cipher.decryptor()
        return dec.update(data) + dec.finalize()

    def desfire_crc32(self, data: bytes) -> bytes:
        """計算符合 MIFARE DESFire 規範的 4-byte CRC32 (位元反轉 + Little-Endian)"""
        crc = zlib.crc32(data) ^ 0xFFFFFFFF
        return crc.to_bytes(4, byteorder="little")

    def pad_zero(self, data: bytes, block_size: int = 16) -> bytes:
        """補 0x00 至 16 Bytes 的整數倍"""
        remainder = len(data) % block_size
        if remainder == 0:
            return data
        return data + (b'\x00' * (block_size - remainder))

    def log(self, msg: str, tag: str = None):
        self.log_area.insert(tk.END, msg + "\n", tag)
        self.log_area.see(tk.END)

    def authenticate(self):
        self.log_area.delete(1.0, tk.END)
        try:
            key = bytes.fromhex(self.key_var.get().strip())
            if len(key) != 16:
                raise ValueError("金鑰必須為 16 Bytes")
        except Exception as e:
            self.log(f"[錯誤] {e}", "err")
            return

        # 模擬快速完成雙向認證並生成 Session Key
        rnd_a = os.urandom(16)
        rnd_b = os.urandom(16)
        self.session_key = rnd_a[0:4] + rnd_b[0:4] + rnd_a[12:16] + rnd_b[12:16]
        self.current_iv = b'\x00' * 16  # 認證後 IV 重置為全 0

        self.session_lbl.config(
            text=f"目前 Session Key: {self.session_key.hex().upper()} (已連線)",
            foreground="#008000"
        )
        self.send_btn.config(state="normal")

        self.log("=== 雙向認證成功!已建立動態會話金鑰 ===", "title")
        self.log(f"RndA        : {rnd_a.hex().upper()}", "hex")
        self.log(f"RndB        : {rnd_b.hex().upper()}", "hex")
        self.log(f"Session Key : {self.session_key.hex().upper()}", "ok")
        self.log(f"初始 IV     : {self.current_iv.hex().upper()}\n", "hex")

    def transfer_data(self):
        if not self.session_key:
            return

        raw_text = self.data_var.get().encode("utf-8")
        # DESFire WriteData 指令檔頭: CMD(0x3D) + FileNo(0x01) + Offset(3B) + Length(3B)
        cmd_header = bytes.fromhex("3D01000000") + len(raw_text).to_bytes(3, "little")

        self.log("--------------------------------------------------")
        self.log("[讀卡機端] 準備加密封包 (WriteData)", "title")
        self.log(f"1. 明文指令檔頭 (不加密) : {cmd_header.hex().upper()}", "hex")
        self.log(f"2. 原始寫入明文 (UTF-8)  : {raw_text.decode('utf-8')} ({raw_text.hex().upper()})")

        # 計算 CRC32 (包含檔頭與明文)
        crc = self.desfire_crc32(cmd_header + raw_text)
        padded_payload = self.pad_zero(raw_text + crc)

        self.log(f"3. 附加 4-Byte CRC32     : {crc.hex().upper()}", "hex")
        self.log(f"4. 補零對齊 16-Byte 區塊 : {padded_payload.hex().upper()}", "hex")

        # 使用 Session Key 與當前 IV 進行 AES-CBC 加密
        encrypted_payload = self.aes_cbc_encrypt(self.session_key, self.current_iv, padded_payload)
        rf_packet = cmd_header + encrypted_payload

        self.log(f"5. 空中傳輸完整 RF 封包  : {rf_packet.hex().upper()}", "title")

        # --- 模擬卡片端接收、解密與驗證 ---
        self.log("\n[卡片端] 接收封包並執行解密驗證", "title")
        rx_header = rf_packet[:8]
        rx_cipher = rf_packet[8:]
        data_len = int.from_bytes(rx_header[5:8], "little")

        decrypted_block = self.aes_cbc_decrypt(self.session_key, self.current_iv, rx_cipher)
        rx_plaintext = decrypted_block[:data_len]
        rx_crc = decrypted_block[data_len:data_len + 4]

        # 卡片重新計算 CRC32 進行比對
        expected_crc = self.desfire_crc32(rx_header + rx_plaintext)

        self.log(f"1. 卡片解密還原區塊      : {decrypted_block.hex().upper()}", "hex")
        self.log(f"2. 擷取明文資料          : {rx_plaintext.decode('utf-8', errors='ignore')}")
        self.log(f"3. 驗證 CRC32 校驗碼     : 收到 {rx_crc.hex().upper()} / 預期 {expected_crc.hex().upper()}")

        if rx_crc == expected_crc:
            # 更新 IV 為本次密文的最後 16 Bytes (DESFire EV1/EV2 連鎖規範)
            self.current_iv = encrypted_payload[-16:]
            self.log("-> [驗證通過] 資料完整且未遭竄改!卡片已寫入記憶體。", "ok")
            self.log(f"-> [IV 狀態更新] 下次通訊初始向量變更為: {self.current_iv.hex().upper()}\n", "hex")
        else:
            self.log("-> [驗證失敗] CRC32 不符,資料可能遭竄改!", "err")

if __name__ == "__main__":
    root = tk.Tk()
    app = DESFireDataTransferApp(root)
    root.mainloop()
3. 觀察重點與實務防護機制
在程式介面中連續點擊幾次「2. 加密傳送並驗證」,即使輸入的明文完全相同,每次產生的「空中傳輸完整 RF 封包」都會截然不同,這背後的關鍵機制如下:
  • 明文檔頭與密文分離。 指令代碼(0x3D 代表 WriteData)與檔案編號(0x01)必須以明文傳送,卡片才能知道要將資料寫入哪個檔案;但真正的資料負載(Payload)與 CRC32 則完全加密。
  • CRC32 納入明文檔頭計算。 計算 CRC32 時,連同未加密的指令檔頭一起算進去。如果攻擊者在傳輸途中試圖將「寫入檔案 01」竄改成「寫入檔案 02」,卡片解密後算出的 CRC32 就會不符並直接拒絕執行。
  • 動態鏈結 IV(Chained IV)。 每次成功傳輸後,程式碼中的 self.current_iv 都會更新為「上一包密文的最後 16 個位元組」。這意味著整個連線期間的所有封包都是前後相扣的,攻擊者無法抽換或重複發送任何一筆歷史封包。




使用 Python + Tkinter + SQLite 製作的「簡易通訊錄」桌面應用程式

使用 Python + Tkinter + SQLite 製作的「簡易通訊錄」桌面應用程式 這個版本不需要額外安裝任何第三方套件(皆為 Python 內建標準函式庫),資料會自動儲存在本地的 contacts.db 資料庫中,並支援 新增、修改、刪除、關鍵字搜尋 以及 匯出 ...