今日學習目標是了解如何在 MySQL 中將敏感病歷欄位(病人姓名、診斷、生命徵象)進行加密後存入資料庫,確保資料即使在資料庫中也不是明文,提升資料安全性。
一、理論重點
二、案例分享
2021 年,台北某大型醫療院所「健安醫院」在內部資安稽核中發現,部分病歷資料(病人姓名、診斷、用藥紀錄)以明文形式存放在資料庫中,存在被內部或外部未授權人員查看或竄改的風險。
為了改善,資訊部門導入 欄位加密機制:當護理師輸入病歷時,系統自動將敏感欄位使用 AES 加密後存入 SQLite 資料庫;資料查詢時也需解密顯示。這個措施確保即便資料庫遭駭客入侵,取得的都是加密資料,降低敏感資料洩漏的風險。
三、簡單程式示範
# day15_insert_encrypted.py
import mysql.connector
from cryptography.fernet import Fernet
# ====== 1. 生成 Fernet key(或使用固定 key) ======
key = Fernet.generate_key()
cipher = Fernet(key)
print("請保存此 key 用於解密:", key.decode())
# ====== 2. 連線到 MySQL ======
conn = mysql.connector.connect(
host="localhost",
user="root",
password="我的密碼",
database="health"
)
cur = conn.cursor()
# ====== 3. 建立病歷資料表 ======
cur.execute("DROP TABLE IF EXISTS patient_records")
cur.execute("""
CREATE TABLE patient_records (
id INT AUTO_INCREMENT PRIMARY KEY,
patient_name VARBINARY(255),
diagnosis VARBINARY(255),
vitals VARBINARY(255)
)
""")
# ====== 4. 插入加密病歷資料 ======
patients = [
{"name": "Alice", "diagnosis": "Diabetes Type 2", "vitals": "BP:120/80, HR:72"},
{"name": "Bob", "diagnosis": "Hypertension", "vitals": "BP:140/90, HR:80"}
]
for p in patients:
enc_name = cipher.encrypt(p["name"].encode())
enc_diag = cipher.encrypt(p["diagnosis"].encode())
enc_vitals = cipher.encrypt(p["vitals"].encode())
cur.execute(
"INSERT INTO patient_records (patient_name, diagnosis, vitals) VALUES (%s, %s, %s)",
(enc_name, enc_diag, enc_vitals)
)
conn.commit()
print("病歷資料已加密並插入 MySQL!")
conn.close()
這樣今天就完成了加密及插入的步驟。結果會顯示一串Key。