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 個位元組」。這意味著整個連線期間的所有封包都是前後相扣的,攻擊者無法抽換或重複發送任何一筆歷史封包。


沒有留言:
張貼留言