今日將加密、Token 驗證、資料庫安全、IoT 資料傳輸、區塊鏈及 AI 安全監控等模組整合為完整醫療資安系統。
一、理論重點
二、案例分享
2021 年法國 Viamed 集團旗下多家醫院遭受勒索病毒攻擊,導致電子病歷系統(EHR)全面停擺超過一週,手術與掛號流程被迫改以紙本處理,超過 30,000 筆病歷外洩。事後調查發現,駭客是透過外包維護系統的弱密碼進入伺服器。這起事件促使歐洲醫療體系重新審視零信任架構與資料加密政策,許多醫院因此建立獨立的區塊鏈式日誌與異常偵測系統。這個案例提醒我們,醫療資安的核心不僅是防駭,而是建立可驗證、可追蹤的安全文化。
三、簡單程式範例
"""
醫療數據的資安挑戰與創新解決方案
Day 1–30 完整整合版程式示範
作者:陳芳俞 (412570388)
"""
# --- 匯入必要套件 ---
from cryptography.fernet import Fernet
from fastapi import FastAPI, Request, HTTPException
import hashlib, time, os, mysql.connector
from sklearn.ensemble import IsolationForest
import numpy as np
app = FastAPI()
# ==========================================================
# Day 3–5:AES / RSA 加密示範
# ==========================================================
key = Fernet.generate_key()
cipher = Fernet(key)
def encrypt_data(data: str) -> bytes:
return cipher.encrypt(data.encode())
def decrypt_data(token: bytes) -> str:
return cipher.decrypt(token).decode()
print("AES 加密測試:", decrypt_data(encrypt_data("Patient A - Diabetes")))
# ==========================================================
# Day 7:JWT + RBAC 模擬
# ==========================================================
TOKENS = {"doctor123": "doctor", "patient123": "patient"}
def verify_token(token: str, role: str):
if TOKENS.get(token) != role:
raise HTTPException(status_code=401, detail="Unauthorized")
# ==========================================================
# Day 9–10:IoT 裝置上傳 + 資料庫儲存
# ==========================================================
def init_mysql():
conn = mysql.connector.connect(
host="localhost", user="root", password="your_password", database="health"
)
cur = conn.cursor()
cur.execute("""
CREATE TABLE IF NOT EXISTS blood_pressure (
id INT AUTO_INCREMENT PRIMARY KEY,
device_id VARCHAR(50),
systolic INT, diastolic INT, pulse INT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
""")
conn.commit()
conn.close()
init_mysql()
@app.post("/upload")
async def upload(request: Request):
data = await request.json()
conn = mysql.connector.connect(
host="localhost", user="root", password="your_password", database="health"
)
cur = conn.cursor()
cur.execute(
"INSERT INTO blood_pressure (device_id, systolic, diastolic, pulse) VALUES (%s, %s, %s, %s)",
(data["device_id"], data["systolic"], data["diastolic"], data["pulse"])
)
conn.commit()
conn.close()
return {"status": "ok", "record": data}
# ==========================================================
# Day 17:區塊鏈病歷共享概念
# ==========================================================
class Block:
def __init__(self, index, timestamp, patient, diagnosis, prev_hash):
self.index = index
self.timestamp = timestamp
self.patient = patient
self.diagnosis = diagnosis
self.prev_hash = prev_hash
self.hash = self.calc_hash()
def calc_hash(self):
record = f"{self.index}{self.timestamp}{self.patient}{self.diagnosis}{self.prev_hash}"
return hashlib.sha256(record.encode()).hexdigest()
class Blockchain:
def __init__(self):
self.chain = [Block(0, time.time(), "Genesis", "Start", "0")]
def add(self, patient, diag):
prev = self.chain[-1]
self.chain.append(Block(len(self.chain), time.time(), patient, diag, prev.hash))
bc = Blockchain()
bc.add("Alice", "Diabetes")
bc.add("Bob", "Hypertension")
print("區塊鏈筆數:", len(bc.chain))
# ==========================================================
# Day 19–20:病人同意分享紀錄(Smart Contract 模擬)
# ==========================================================
class Consent:
def __init__(self):
self.data = {}
def give(self, p):
self.data[p] = True
print(p, "同意分享")
def revoke(self, p):
self.data[p] = False
print(p, "撤回同意")
consent = Consent()
consent.give("PatientA")
consent.revoke("PatientA")
# ==========================================================
# Day 24:勒索病毒模擬(教育用途)
# ==========================================================
def fake_encrypt_folder(folder):
if not os.path.exists(folder):
os.makedirs(folder)
for file in os.listdir(folder):
if file.endswith(".txt"):
fp = os.path.join(folder, file)
with open(fp, "rb") as f:
data = f.read()
with open(fp, "wb") as f:
f.write(cipher.encrypt(data))
print("模擬加密完成")
# ==========================================================
# Day 29:AI 偵測異常(Isolation Forest)
# ==========================================================
model = IsolationForest(contamination=0.1)
X = np.array([[120,80,70],[200,100,90],[118,76,68],[300,180,100]])
model.fit(X)
pred = model.predict([[250,150,85]])[0]
print("異常偵測結果:", "異常" if pred == -1 else "正常")
# ==========================================================
# 主程式啟動提示
# ==========================================================
if __name__ == "__main__":
print("Medical Data Security Demo Ready.")
四、心得
這 30 天的挑戰讓我從理論走向實務,真正理解「醫療資安」不只是技術題,而是信任與責任的延伸。從最初的加密原理、API 驗證、資料庫安全,到 IoT 傳輸與 AI 偵測異常,我學會如何讓資料在每一個節點都被保護。整個過程雖然繁瑣,但看到系統能安全地上傳、儲存並防護病歷資料時,成就感也隨之而來。