iT邦幫忙

2025 iThome 鐵人賽

DAY 3
0
Security

醫療數據的資安挑戰與創新解決方案系列 第 3

加密基本原理與 Python 實作

  • 分享至 

  • xImage
  •  

今天的學習目標是理解加密的基本概念(對稱加密、非對稱加密與雜湊),並透過簡單程式實作,學會如何將醫療數據進行基本保護。

一、 加密的三種常見方式

  • 對稱加密 (Symmetric Encryption)
    使用同一把金鑰進行加密與解密,速度快,適合大量資料,但金鑰管理是挑戰。
    常見演算法:AES

  • 非對稱加密 (Asymmetric Encryption)
    使用公鑰加密、私鑰解密,適合資料傳輸或身份驗證。
    常見演算法:RSA

  • 雜湊 (Hashing)
    不可逆,用來驗證資料完整性(例如病歷是否被竄改)。
    常見演算法:SHA-256

二、實際案例分享
2017 年美國的一間醫療機構,因為病歷系統中的資料只做存取控制卻沒有加密,導致駭客入侵伺服器後,直接取得上萬筆未加密的病患紀錄。最後醫院被迫支付鉅額罰款,並重新建置完整的加密系統。這顯示了「沒有加密」就等於資料赤裸暴露,即便有帳號密碼保護也不足。

三、簡單程式示範

  • 對稱加密(AES / Fernet)
from cryptography.fernet import Fernet

# 產生金鑰
key = Fernet.generate_key()
cipher = Fernet(key)

# 模擬病歷資料
medical_record = "Patient: 王小明, Diagnosis: 高血壓, Medicine: Amlodipine"

# 加密
encrypted = cipher.encrypt(medical_record.encode())
print("🔒 加密後資料:", encrypted)

# 解密
decrypted = cipher.decrypt(encrypted).decode()
print("🔓 解密後資料:", decrypted)

以上執行的結果如下
https://ithelp.ithome.com.tw/upload/images/20250912/20169331CzAPElzJvS.png

  • 非對稱加密(RSA)
from cryptography.hazmat.primitives.asymmetric import rsa, padding
from cryptography.hazmat.primitives import serialization, hashes

# 產生 RSA 公私鑰
private_key = rsa.generate_private_key(
    public_exponent=65537,
    key_size=2048
)
public_key = private_key.public_key()

# 模擬病歷資料
medical_record = "Patient: 王小明, Diagnosis: 糖尿病, Medicine: Metformin"

# 公鑰加密
encrypted = public_key.encrypt(
    medical_record.encode(),
    padding.OAEP(
        mgf=padding.MGF1(algorithm=hashes.SHA256()),
        algorithm=hashes.SHA256(),
        label=None
    )
)
print("🔒 公鑰加密後資料:", encrypted)

# 私鑰解密
decrypted = private_key.decrypt(
    encrypted,
    padding.OAEP(
        mgf=padding.MGF1(algorithm=hashes.SHA256()),
        algorithm=hashes.SHA256(),
        label=None
    )
)
print("🔓 私鑰解密後資料:", decrypted.decode())

非對稱加密常用於金鑰交換與身份驗證,公鑰加密、私鑰解密。執行結果如下
https://ithelp.ithome.com.tw/upload/images/20250912/20169331HvXm2b89I1.png

  • 雜湊(SHA-256)
import hashlib

# 模擬病歷資料
medical_record = "Patient: 王小明, Diagnosis: 氣喘, Medicine: Salbutamol"

# SHA-256 雜湊
hash_value = hashlib.sha256(medical_record.encode()).hexdigest()
print("🔑 病歷 SHA-256 雜湊值:", hash_value)

# 測試竄改
tampered_record = "Patient: 王小明, Diagnosis: 心臟病, Medicine: Salbutamol"
tampered_hash = hashlib.sha256(tampered_record.encode()).hexdigest()

print("⚠️ 篡改後雜湊:", tampered_hash)
print("✅ 是否一致?", hash_value == tampered_hash)

雜湊不可逆,用於驗證資料完整性,例如檢查病歷有沒有被竄改。執行結果如下
https://ithelp.ithome.com.tw/upload/images/20250912/20169331GDvT3g7dmb.png

加密是醫療資訊安全的第一道防線,不論是存在資料庫、雲端,或是 IoT 裝置的傳輸,都應採用加密技術,確保即便資料外洩,也難以被利用。


上一篇
醫療資訊安全法規與資料標準
系列文
醫療數據的資安挑戰與創新解決方案3
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言