?? 零基礎(chǔ)入門學(xué)習(xí)Python?? |
?? 算法刷題專欄 | 面試必備算法 | 面試高頻算法 ??
?? 越難的東西,越要努力堅持,因?yàn)樗哂泻芨叩膬r值,算法就是這樣?
?? 作者簡介:碩風(fēng)和煒,CSDN-Java領(lǐng)域優(yōu)質(zhì)創(chuàng)作者??,保研|國家獎學(xué)金|高中學(xué)習(xí)JAVA|大學(xué)完善JAVA開發(fā)技術(shù)棧|面試刷題|面經(jīng)八股文|經(jīng)驗(yàn)分享|好用的網(wǎng)站工具分享??????
?? 恭喜你發(fā)現(xiàn)一枚寶藏博主,趕快收入囊中吧??
?? 人生如棋,我愿為卒,行動雖慢,可誰曾見我后退一步?????
?? 零基礎(chǔ)入門學(xué)習(xí)Python?? |
?? Python安全編程和測試
Python 在網(wǎng)絡(luò)安全和測試領(lǐng)域有著廣泛的應(yīng)用,如 Web 應(yīng)用開發(fā),安全測試,ETL 流程,數(shù)據(jù)分析等,本文將介紹 Python 安全編程和測試的基本原則和技術(shù),以及常見的安全漏洞和攻擊方式。
?? 安全編程的基本原則和技術(shù)
?? 數(shù)據(jù)驗(yàn)證
在編寫 Python 程序時,保證對輸入數(shù)據(jù)的驗(yàn)證是很重要的。數(shù)據(jù)驗(yàn)證是指對輸入數(shù)據(jù)的正確性和安全性進(jìn)行檢驗(yàn),從而防止惡意攻擊者利用惡意數(shù)據(jù)破壞程序。
以下是一些常見的數(shù)據(jù)驗(yàn)證技術(shù):
- 輸入長度驗(yàn)證。
- 輸入指定字符的驗(yàn)證,如數(shù)字,字母和符號。
- 輸入數(shù)據(jù)的格式驗(yàn)證,如郵箱和手機(jī)號碼。
- 預(yù)處理用戶輸入數(shù)據(jù),去除不必要的字符和標(biāo)簽。
import re
email_regex = re.compile(r"[^@]+@[^@]+\.[^@]+")
def is_valid_email_address(email):
"""
校驗(yàn)電子郵件地址。
"""
if not email:
return False
return email_regex.match(email) is not None
print(is_valid_email_address("foo@example.com"))
print(is_valid_email_address("bar@test"))
?? 減少代碼注入風(fēng)險
Python 中的執(zhí)行代碼注入風(fēng)險被廣泛利用,例如在處理不能信任的數(shù)據(jù)時,如網(wǎng)絡(luò)爬蟲、Web 應(yīng)用程序和數(shù)據(jù)處理程序。 這些程序需要經(jīng)常處理動態(tài)的輸入數(shù)據(jù),惡意攻擊者可能使用這些數(shù)據(jù)注入惡意代碼。
以下是一些減少代碼注入風(fēng)險的技術(shù):
- 使用 Python 內(nèi)置的編碼和解碼模塊進(jìn)行 URL、XML、JSON 的加解密處理,減少注入攻擊的風(fēng)險。
- 使用 Paramiko API 網(wǎng)絡(luò)連接模塊,支持 SSH 和 Telnet 協(xié)議。
# 使用 XML 模塊解析惡意 XML 數(shù)據(jù)
import xml.etree.ElementTree as ET
def get_element_value(xml_string, element_name):
"""
獲取 XML 元素值。
"""
root = ET.fromstring(xml_string)
return root.findtext(element_name)
?? 防止敏感數(shù)據(jù)泄露
在處理敏感數(shù)據(jù)時,防止敏感數(shù)據(jù)泄露是非常重要的,如數(shù)據(jù)庫連接密碼、敏感配置文件等。為避免敏感數(shù)據(jù)泄露,可以使用如下的技術(shù):
- 在處理敏感數(shù)據(jù)時,盡量不要使用明文存儲,例如使用哈希合適的算法存儲密碼,保證安全性。
- 使用環(huán)境變量或者配置文件等把敏感數(shù)據(jù)存儲到特定的位置。
- 對敏感數(shù)據(jù)進(jìn)行專門的加密和解密,如 AES,RSA,MD5 等。
import hashlib
def md5_encode(password: str) -> str:
"""
使用 md5 加密方式對密碼進(jìn)行加密。
"""
md5 = hashlib.md5()
md5.update(password.encode("utf-8"))
return md5.hexdigest()
?? 常見的安全漏洞和攻擊方式
了解常用的安全漏洞和攻擊方式是非常重要的,以下是一些常見的安全漏洞和攻擊方式:
?? SQL 注入攻擊
在 Web 應(yīng)用程序中 SQL 注入攻擊被廣泛利用,例如查詢惡意語句的內(nèi)容或者修改數(shù)據(jù)庫等,為避免 SQL 注入攻擊,應(yīng)在構(gòu)造 SQL 語句時使用預(yù)定義查詢,或使用數(shù)據(jù)庫的原生語句,防止惡意的 SQL 數(shù)據(jù)注入。
import sqlite3
def get_user_data(user_id: int):
"""
從數(shù)據(jù)庫獲取用戶信息,使用綁定參數(shù)方式防止 SQL 注入攻擊。
"""
with sqlite3.connect("example.db") as conn:
cursor = conn.cursor()
cursor.execute("SELECT * FROM user WHERE id = ?", (user_id,))
row = cursor.fetchone()
if row:
return {"id": row[0], "username": row[1], "email": row[2]}
print(get_user_data(1))
?? XSS 跨站腳本攻擊
在 Web 應(yīng)用程序中,XSS 攻擊通常利用網(wǎng)頁編譯程序的漏洞,通過注入惡意腳本來控制用戶的瀏覽器。為避免 XSS 攻擊,可以使用框架內(nèi)置的 XSS 過濾器或編寫自己的 XSS 過濾器,對用戶的輸入進(jìn)行過濾。
以下是一個示例代碼,用于從 HTML 中過濾惡意腳本:
import html
def html_escape(text):
"""
轉(zhuǎn)義 HTML 中的非法字符,防止 XSR 攻擊。
"""
return html.escape(text)
html = """
<html>
<head>
<title>安全編程的示例代碼</title>
</head>
<body>
<script>alert('注入攻擊!')</script>
<div>{{ content }}</div>
</body>
</html>
"""
print(html_escape(html))
?? 使用加密和哈希算法保護(hù)數(shù)據(jù)
保護(hù)數(shù)據(jù)的安全性是非常關(guān)鍵的,特別是在處理敏感數(shù)據(jù)時更是必要的。常用的加密和哈希算法包括 MD5,SHA,AES,RSA 等。
以下是一個使用 AES 加密算法的示例代碼,對用戶的輸入密碼進(jìn)行加密存儲和解密:
import base64
import hashlib
from Crypto.Cipher import AES
class AESEncrypt:
"""
加解密邏輯處理。
"""
key = hashlib.md5("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx".encode("utf-8")).digest()
def __init__(self):
self.mode = AES.MODE_CBC
self.Iv = b'0000000000000000'
def encrypt(self, text):
cryptor = AES.new(self.key, self.mode, self.Iv)
length = 16
count = len(text.encode("utf-8"))
add = length - (count % length)
text += (b'\0' * add).decode("utf-8")
self.ciphertext = cryptor.encrypt(text.encode("utf-8"))
return base64.b64encode(self.ciphertext)
def decrypt(self, text):
cryptor = AES.new(self.key, self.mode, self.Iv)
plain_text = cryptor.decrypt(base64.b64decode(text))
return plain_text.rstrip(b'\0').decode("utf-8")
aes = AESEncrypt()
original_password = "123456"
en_password = aes.encrypt(original_password)
print(f"original password: {original_password}")
print(f"encrypted password: {en_password.decode('utf-8')}")
print(f"decrypt password: {aes.decrypt(en_password)}")
assert original_password == aes.decrypt(en_password)
?? 編寫安全的 Web 應(yīng)用和 API
在編寫 Web 應(yīng)用和 API 時,需要遵循以下的安全性原則:
- 使用 HTTPS 協(xié)議,保證連接安全。
- 應(yīng)保護(hù)用戶會話,避免惡意攻擊者通過會話劫持竊取會話信息。
- 認(rèn)證和授權(quán)的原則,確保連目標(biāo)的 API 和服務(wù)只能由授權(quán)的用戶使用。
- 數(shù)據(jù)和交互的驗(yàn)證原則,確保用戶輸入和應(yīng)用程序交互的有效性。
- 監(jiān)控和日志,對應(yīng)用程序的運(yùn)行時行為進(jìn)行記錄。
以下是一個示例代碼,用于展示如何使用 Flask 來編寫一個基本的 Web 應(yīng)用和 API:
from flask import Flask, jsonify, request
app = Flask(__name__)
@app.route("/", methods=["GET"])
def home():
"""
返回 API 首頁。
"""
response = {"message": "歡迎來到 Python 安全編程 API!"}
return jsonify(response)
@app.route("/login", methods=["POST"])
def login():
"""
登錄接口。
"""
username = request.form.get("username")
password = request.form.get("password")
if authenticate(username, password):
token = generate_token"""
## 編寫安全的 Web 應(yīng)用和 API(續(xù))
以下是一個示例代碼,用于展示如何使用 Flask 來編寫一個基本的 Web 應(yīng)用和 API:
```python
from flask import Flask, jsonify, request
app = Flask(__name__)
@app.route("/", methods=["GET"])
def home():
"""
返回 API 首頁。
"""
response = {"message": "歡迎來到 Python 安全編程 API!"}
return jsonify(response)
@app.route("/login", methods=["POST"])
def login():
"""
登錄接口。
"""
username = request.form.get("username")
password = request.form.get("password")
if authenticate(username, password):
token = generate_token(username)
return jsonify({"token": token.decode("utf-8")})
return jsonify({"error": "用戶名或密碼錯誤。"}), 401
@app.route("/profile", methods=["GET"])
@auth_required
def profile():
"""
用戶資料。
"""
username = request.headers.get("Authorization")
user = get_user_by_username(username)
return jsonify({"id": user.id, "username": user.username, "email": user.email})
if __name__ == "__main__":
app.run()
在上述代碼中,我們使用了 Flask 框架來編寫一個簡單的 API,并實(shí)現(xiàn)了登錄和用戶資料的接口,以及 JWT 認(rèn)證和授權(quán)的功能。為了保護(hù) API 的安全性,我們定義了一個 auth_required 裝飾器,用于驗(yàn)證 JWT Token 的有效性,防止非法請求訪問接口。
?? 單元測試和集成測試的基本概念
單元測試和集成測試是 Python 安全編程的一個重要方面,其主要目的是為開發(fā)人員提供構(gòu)建可持續(xù)性和可測試性應(yīng)用程序的機(jī)制,并幫助他們實(shí)現(xiàn)高質(zhì)量的代碼。單元測試是指對應(yīng)用程序中單獨(dú)的部分進(jìn)行測試,而集成測試是指考慮應(yīng)用程序的整體性,在構(gòu)建和部署應(yīng)用程序之前測試整個應(yīng)用程序。
以下是一些單元測試和集成測試的基本概念:
?? 單元測試
在 Python 中,unittest 模塊是用于單元測試的標(biāo)準(zhǔn)庫之一,通過使用 TDD(測試驅(qū)動開發(fā))的方式為開發(fā)人員提供了一個基準(zhǔn)測試類和一組斷言方法,易于開發(fā)者編寫簡單,可重復(fù)的自動化測試。
以下是一個使用 unittest 模塊編寫的示例測試用例:
import unittest
class TestStringMethods(unittest.TestCase):
def test_upper(self):
self.assertEqual('foo'.upper(), 'FOO')
def test_isupper(self):
self.assertTrue('FOO'.isupper())
self.assertFalse('Foo'.isupper())
def test_split(self):
s = 'hello world'
print(s)
self.assertEqual(s.split(), ['hello', 'world'])
if __name__ == "__main__":
t=TestStringMethods()
t.test_split()
?? 集成測試
在 Python 中,pytest 模塊是用于集成測試的標(biāo)準(zhǔn)庫之一,可以使用插件和擴(kuò)展模塊擴(kuò)展其功能。pytest 的功能非常強(qiáng)大,可以測試應(yīng)用程序中的所有部分,包括數(shù)據(jù)庫和 API。
以下是一個使用 pytest 模塊編寫的示例測試用例:
import pytest
def test_username():
username = "john_doe_123"
assert username.islower()
def test_password():
password = "password123"
assert len(password) >= 8
?? 使用 unittest 或 pytest 進(jìn)行測試
Python 提供了許多單元測試和集成測試的庫和框架,例如 unittest 和 pytest 等。
unittest 是 Python 內(nèi)置的庫,可以用于簡單而可靠的單元測試,它定義了一組測試框架,支持參數(shù)化測試、測試裝飾器、斷言語句等特性。
以下是一個使用 unittest 編寫的示例測試用例:
import unittest
class TestStringMethods(unittest.TestCase):
def test_upper(self):
self.assertEqual('foo'.upper(), 'FOO')
def test_isupper(self):
self.assertTrue('FOO'.isupper())
self.assertFalse('Foo'.isupper())
def test_split(self):
s = 'hello world'
self.assertEqual(s.split(), ['hello', 'world'])
pytest 是 Python 中一個非常流行的測試框架,支持功能強(qiáng)大、可配置和易于擴(kuò)展,并且不需要類的繼承。
以下是一個使用 pytest 編寫的示例測試用例:
import pytest
def test_username():
username = "john_doe_123"
assert username.islower()
def test_password():
password = "password123"
assert len(password) >= 8
?? 測試驅(qū)動開發(fā)(TDD)的實(shí)踐
測試驅(qū)動開發(fā)(TDD)是一種受歡迎的開發(fā)方法,它是一種理想的方式,可以在編寫代碼之前先編寫測試用例,并在完成代碼后進(jìn)行自動化測試,以保證代碼的正確性。
使用 TDD 開發(fā) Python 安全編程應(yīng)用程序時,我們可以遵循以下的流程:
- 編寫測試用例。
- 運(yùn)行測試用例,檢查測試是否失敗。
- 編寫代碼,讓測試用例通過。
- 運(yùn)行測試用例,檢查是否成功通過。
以下是一個使用 TDD 開發(fā)的示例代碼:
def get_user_data(user_id):
"""
獲取用戶數(shù)據(jù)。
"""
conn = get_database_connection()
cursor = conn.cursor()
cursor.execute("SELECT * FROM users WHERE id = %s", (user_id,))
rows = cursor.fetchall()
if rows:
return rows[0]
return None
def test_get_user_data():
"""
用于測試獲取用戶數(shù)據(jù)的函數(shù)。
"""
user_id = 1
user_data = get_user_data(user_id)
assert user_data is not None
在上面的示例代碼中,我們首先編寫一個獲取用戶數(shù)據(jù)的函數(shù)的測試用例,然后實(shí)現(xiàn)這個函數(shù),最后運(yùn)行測試用例,確保函數(shù)的正確性和安全性。
?? 結(jié)論
本文介紹了如何在 Python 中進(jìn)行安全編程和測試,包括數(shù)據(jù)驗(yàn)證,減少代碼注入風(fēng)險,防止敏感數(shù)據(jù)泄露,常見的安全漏洞和攻擊方式,使用加密和哈希算法保護(hù)數(shù)據(jù),編寫安全的 Web 應(yīng)用和 API,單元測試和集成測試的基本概念,使用 unittest 或 pytest 進(jìn)行測試,測試驅(qū)動開發(fā)(TDD)的實(shí)踐等方面,并提供了示例代碼,幫助開發(fā)者更好的理解 Python 安全編程和測試的概念和實(shí)踐。
?? 共勉
最后,我想和大家分享一句一直激勵我的座右銘,希望可以與大家共勉! |
文章來源:http://www.zghlxwxcb.cn/news/detail-524515.html
文章來源地址http://www.zghlxwxcb.cn/news/detail-524515.html
到了這里,關(guān)于【零基礎(chǔ)入門學(xué)習(xí)Python---Python中安全編程和測試之快速入門實(shí)踐】的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!