2025年3月6日 星期四

Python 18 小時入門--第 17 小時:Python 資安與測試(Security & Testing)

 📌 第 17 小時:Python 資安與測試(Security & Testing)

開發 Python 應用程式時,安全性與測試至關重要。本章將介紹:

  1. Python 應用的安全風險
  2. 防範 SQL Injection(SQL 注入攻擊)
  3. 密碼雜湊與加密
  4. 使用 unittest 進行單元測試
  5. 使用 pytest 進行自動化測試
  6. API 測試與 Postman

🔹 1. Python 應用的安全風險

開發 Web 應用與 API 時,常見的安全風險包括:

攻擊類型 說明 解決方案
SQL Injection(SQL 注入) 透過惡意 SQL 操作資料庫 使用參數化查詢
XSS(跨站腳本攻擊) 在網頁中插入惡意 JavaScript 避免直接輸出未經處理的用戶輸入
CSRF(跨站請求偽造) 利用受信任用戶發送惡意請求 使用 CSRF Token
弱密碼 使用簡單密碼容易被破解 使用密碼雜湊(bcrypt, SHA256)

📌 防禦策略

  • 永遠不要信任用戶輸入
  • 使用加密技術保護密碼
  • 定期更新套件,修補安全漏洞

🔹 2. 防範 SQL Injection(SQL 注入攻擊)

惡意攻擊者可能會輸入 ' OR 1=1 -- 這類字串來繞過驗證,獲取未授權的數據。

🟢 危險範例(SQL Injection)

import sqlite3

conn = sqlite3.connect("example.db")
cursor = conn.cursor()

username = input("輸入用戶名: ")  # 用戶輸入 ' OR 1=1 --
query = f"SELECT * FROM users WHERE username = '{username}'"

cursor.execute(query)  # ⚠️ 這樣會讓駭客獲取所有數據

🟢 安全做法:使用參數化查詢

cursor.execute("SELECT * FROM users WHERE username = ?", (username,))

📌 這樣的查詢不會被惡意 SQL 語法影響。


🔹 3. 密碼雜湊與加密

存儲用戶密碼時,應該使用雜湊算法加密,而不是明文存放。

🟢 使用 bcrypt 進行密碼加密

pip install bcrypt
import bcrypt

# 生成密碼雜湊
password = "mypassword"
hashed = bcrypt.hashpw(password.encode(), bcrypt.gensalt())

print(hashed)  # 儲存這個雜湊到資料庫

🟢 驗證密碼

if bcrypt.checkpw("mypassword".encode(), hashed):
    print("密碼正確")
else:
    print("密碼錯誤")

📌 即使駭客獲取了密碼雜湊,也無法輕易破解。


🔹 4. 使用 unittest 進行單元測試

測試可以確保程式的正確性,unittest 是 Python 內建的測試框架。

🟢 建立測試

import unittest

def add(x, y):
    return x + y

class TestMath(unittest.TestCase):
    def test_add(self):
        self.assertEqual(add(2, 3), 5)
        self.assertEqual(add(-1, 1), 0)

if __name__ == "__main__":
    unittest.main()

📌 這會自動測試 add(2, 3) 是否等於 5


🔹 5. 使用 pytest 進行自動化測試

pytestunittest 更簡潔,適合大規模測試。

🟢 安裝 pytest

pip install pytest

🟢 撰寫 test_math.py

def add(x, y):
    return x + y

def test_add():
    assert add(2, 3) == 5
    assert add(-1, 1) == 0

🟢 執行測試

pytest

📌 pytest 會自動執行 test_ 開頭的函式。


🔹 6. API 測試與 Postman

開發 API 時,可以使用 Postman 進行測試:Postman 官方網站

🟢 Flask API 測試

from flask import Flask, jsonify

app = Flask(__name__)

@app.route("/api")
def api():
    return jsonify({"message": "Hello, API!"})

if __name__ == "__main__":
    app.run(debug=True)

📌 啟動後,可用 Postman 測試 http://127.0.0.1:5000/api


📌 第 17 小時小結

防止 SQL Injection,使用參數化查詢
密碼應使用 bcrypt 雜湊存儲,避免明文存放
unittest & pytest 可用於自動化測試,確保程式正確性
使用 Postman 測試 API,確保 Web 服務運作正常

學完這一章,你已掌握 Python 應用的安全性與測試方法,下一步將學習 Python 自動化與爬蟲進階應用!🚀

沒有留言:

張貼留言