現今網路安全環境下,資料保護至關重要。本文介紹 Python 加密解密技術,從 ZIP 檔案密碼破解到 AES 和 RSA 加密演算法,並涵蓋 PBKDF2 金鑰衍生函式與安全金鑰生成方法。文章提供實務程式碼,演示如何使用 Python 內建的 zipfile 模組、pyminizip 模組和 cryptography 函式庫操作 ZIP 檔案、實作對稱與非對稱加密,以及安全地生成金鑰。同時,也說明如何運用 AES-GCM 模式提升資料保護,並透過流程圖和類別圖,讓讀者更清晰地理解加密解密流程和 AES 類別的應用。
破解 ZIP 檔案密碼:從原理到實踐
在數位世界中,檔案安全至關重要。ZIP 檔案格式以其無失真壓縮和密碼保護功能,廣泛應用於資料儲存和傳輸。本文將探討如何使用 Python 建立帶密碼的 ZIP 檔案,並運用暴力破解法取得密碼以提取檔案內容。
Python 與 ZIP 檔案處理
Python 提供了強大的 zipfile 模組,讓開發者能輕鬆處理 ZIP 檔案。以下是一些常用的操作:
建立 ZIP 檔案
import os
import zipfile
def create_zip(zip_name, source_dir):
with zipfile.ZipFile(zip_name, "w") as zf:
for dirname, subdirs, files in os.walk(source_dir, topdown=False):
for filename in files:
zf.write(os.path.join(dirname, filename))
# 建立名為 archive.zip 的檔案,壓縮 source_files 資料夾下的所有檔案
create_zip("archive.zip", "source_files")
內容解密:
這段程式碼利用 os.walk 遍歷指定目錄下的所有檔案,並使用 zipfile.ZipFile 物件將其寫入 ZIP 檔案。
讀取 ZIP 檔案內容
import zipfile
def list_zip_contents(zip_name):
with zipfile.ZipFile(zip_name, "r") as zf:
for filename in zf.namelist():
print(filename)
# 列出 archive.zip 中的所有檔案
list_zip_contents("archive.zip")
內容解密:
zf.namelist() 方法傳回 ZIP 檔案中所有檔案的列表。
檢視 ZIP 檔案 metadata
import datetime
import zipfile
def show_zip_metadata(zip_name):
with zipfile.ZipFile(zip_name, "r") as zf:
for info in zf.infolist():
print(f"檔案名稱: {info.filename}")
print(f"修改時間: {datetime.datetime(*info.date_time)}")
print(f"壓縮大小: {info.compress_size} bytes")
print(f"原始大小: {info.file_size} bytes")
print("-" * 20)
# 顯示 archive.zip 中所有檔案的 metadata
show_zip_metadata("archive.zip")
內容解密:
zf.infolist() 傳回一個包含 ZipInfo 物件的列表,每個物件儲存了檔案的 metadata,例如修改時間、大小等。
從 ZIP 檔案解壓縮檔案
import zipfile
def extract_zip(zip_name, target_dir, password=None):
try:
with zipfile.ZipFile(zip_name, "r") as zf:
zf.extractall(path=target_dir, pwd=password.encode() if password else None)
except RuntimeError as e:
print(f"解壓縮失敗: {e}")
# 將 archive.zip 解壓縮到 extracted_files 資料夾
extract_zip("archive.zip", "extracted_files")
內容解密:
zf.extractall() 方法可以解壓縮 ZIP 檔案中的所有檔案。pwd 引數用於提供密碼。
建立帶密碼的 ZIP 檔案
Python 內建的 zipfile 模組不支援直接建立帶密碼的 ZIP 檔案。我們可以使用 pyminizip 模組來達成這個目的。
import pyminizip
def create_password_protected_zip(source_file, zip_name, password):
compression_level = 5 # 壓縮等級,1 最快,9 壓縮率最高
pyminizip.compress(source_file, None, zip_name, password, compression_level)
# 建立帶密碼的 ZIP 檔案
create_password_protected_zip("sensitive_data.txt", "protected.zip", "mysecretpassword")
內容解密:
pyminizip.compress() 函式可以直接建立帶密碼的 ZIP 檔案。
暴力破解 ZIP 檔案密碼
以下程式碼示範如何使用暴力破解法嘗試不同的密碼來解壓縮受密碼保護的 ZIP 檔案。
import zipfile
def crack_zip_password(zip_name, dictionary_file):
with open(dictionary_file, "r") as f:
passwords = [line.strip() for line in f]
with zipfile.ZipFile(zip_name, "r") as zf:
for password in passwords:
try:
zf.extractall(pwd=password.encode())
print(f"密碼破解成功: {password}")
return password
except RuntimeError:
pass # 繼續嘗試下一個密碼
print("密碼破解失敗")
return None
# 嘗試破解 protected.zip 的密碼,使用 password_list.txt 中的密碼列表
crack_zip_password("protected.zip", "password_list.txt")
內容解密:
這個函式讀取字典檔中的密碼,並逐個嘗試解壓縮 ZIP 檔案。如果解壓縮成功,則表示密碼破解成功。
暴力破解流程
此圖示說明瞭暴力破解 ZIP 檔案密碼的基本流程:
- 從字典檔讀取可能的密碼。
- 使用每個密碼嘗試解壓縮 ZIP 檔案。
- 如果找到正確的密碼,流程結束於「破解成功」。
- 如果遍歷完所有密碼仍未成功,則流程結束於「破解失敗」。
AES加密演算法詳解與實作
AES(Advanced Encryption Standard)是一種廣泛使用的對稱式區塊加密演算法,用於保護電子資料的機密性。與DES相比,AES支援更長的金鑰長度,提供了更高的安全性。
AES加密的關鍵特性
- 區塊大小: AES的區塊大小固定為128位元(16位元組)。
- 金鑰長度: AES支援128位元、192位元和256位元三種金鑰長度,其中AES-256被認為是最安全的。
- 加密模式: AES支援多種加密模式,包括ECB、CBC、CFB、OFB和CTR等,每種模式都有其特定的應用場景和安全性考量。
使用PyCryptodome實作AES加密
以下是一個使用PyCryptodome函式庫實作AES加密和解密的範例:
from Crypto.Cipher import AES
from Crypto.Random import get_random_bytes
# 生成隨機金鑰和初始向量
key = get_random_bytes(32) # 256位元金鑰
iv = get_random_bytes(16) # 128位元初始向量
# 建立AES加密器
cipher = AES.new(key, AES.MODE_CBC, iv)
# 待加密的資料
data = b"This is a secret message."
# 填充資料至區塊大小的倍數
data_padded = data + b'\x00' * (16 - len(data) % 16)
# 加密資料
encrypted_data = cipher.encrypt(data_padded)
print("Encrypted data:", encrypted_data.hex())
# 建立AES解密器
decipher = AES.new(key, AES.MODE_CBC, iv)
# 解密資料
decrypted_data = decipher.decrypt(encrypted_data)
# 移除填充
decrypted_data = decrypted_data.rstrip(b'\x00')
print("Decrypted data:", decrypted_data.decode())
內容解密:
這段程式碼展示瞭如何使用AES演算法在CBC模式下進行加密和解密。首先,我們生成隨機的金鑰和初始向量(IV),然後建立AES加密器。待加密的資料需要被填充至16位元組(128位元)的倍數,以滿足AES的區塊大小要求。加密後的資料以十六進位制格式輸出。解密過程中,我們使用相同的金鑰和IV建立AES解密器,將加密資料還原為原始明文。
AES加密的安全性考量
- 金鑰管理: AES的安全性高度依賴於金鑰的安全性。金鑰應當安全儲存,避免洩露。
- 初始向量的選擇: IV應當是隨機且不可預測的,以防止攻擊者利用已知的IV進行攻擊。
- 填充方案: 正確的填充方案(如PKCS7填充)可以防止填充預言攻擊。
AES應用場景
AES廣泛應用於各種需要資料加密的場景,包括但不限於:
- 資料儲存加密
- 網路通訊加密(如TLS/SSL)
- 檔案加密工具
透過正確實作和使用AES加密演算法,可以有效保護資料的機密性和完整性。
流程解密: 此流程圖展示了使用AES演算法進行加密和解密的基本過程。明文經過AES加密後變成密鑰,密鑰再經過AES解密後還原成明文。
類別圖說明: 此類別圖展示了AES類別的主要方法,包括new()用於建立加密器物件,encrypt()用於加密,以及decrypt()用於解密。
檔案加密技術詳解與實作
在資訊安全領域,檔案加密是保護敏感資料的關鍵技術。本文將探討兩種常用的加密演算法:AES 和 RSA,並使用 Python 的 pycryptodome 函式庫示範如何進行檔案的加密和解密。
AES 加密解密實戰
AES(Advanced Encryption Standard)是一種對稱加密演算法,使用相同的金鑰進行加密和解密。以下程式碼示範如何使用 AES 進行檔案加密和解密:
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad, unpad
from Crypto.Hash import SHA256
import os
import getpass
def getKey(password):
# 使用 SHA-256 從密碼衍生金鑰
hasher = SHA256.new(password)
return hasher.digest()
def encrypt_file(key, filename):
chunk_size = 64 * 1024
output_filename = filename + '.encrypted'
iv = os.urandom(16) # 使用隨機數產生初始向量
encryptor = AES.new(key, AES.MODE_CBC, iv)
filesize = os.path.getsize(filename)
with open(filename, 'rb') as infile:
with open(output_filename, 'wb') as outfile:
outfile.write(filesize.to_bytes(8, 'big')) # 寫入檔案大小
outfile.write(iv)
while True:
chunk = infile.read(chunk_size)
if len(chunk) == 0:
break
elif len(chunk) % 16 != 0:
chunk = pad(chunk, 16) # 填充資料至 16 的倍數
outfile.write(encryptor.encrypt(chunk))
def decrypt_file(key, filename):
chunk_size = 64 * 1024
output_filename = filename[:-10] # 移除 '.encrypted' 副檔名
with open(filename, 'rb') as infile:
origsize = int.from_bytes(infile.read(8), 'big')
iv = infile.read(16)
decryptor = AES.new(key, AES.MODE_CBC, iv)
with open(output_filename, 'wb') as outfile:
while True:
chunk = infile.read(chunk_size)
if len(chunk) == 0:
break
outfile.write(decryptor.decrypt(chunk))
outfile.truncate(origsize) # 移除填充資料
def main():
choice = input("您要 (E)ncrypt 或 (D)ecrypt?: ")
if choice.upper() == 'E':
filename = input('請輸入要加密的檔案: ')
password = getpass.getpass('請輸入密碼: ')
encrypt_file(getKey(password.encode("utf8")), filename)
print('加密完成.')
elif choice.upper() == 'D':
filename = input('請輸入要解密的檔案: ')
password = getpass.getpass('請輸入密碼: ')
decrypt_file(getKey(password.encode("utf8")), filename)
print('解密完成.')
else:
print('無效的選項.')
if __name__ == "__main__":
main()
內容解密:
這段程式碼定義了檔案加密和解密的函式。getKey 函式使用 SHA-256 演算法從使用者提供的密碼生成金鑰。encrypt_file 函式使用 AES-CBC 模式加密檔案,並將檔案大小和初始向量 (IV) 寫入加密檔案。decrypt_file 函式則進行解密,並移除填充資料以還原始檔案。
程式碼安全性分析
- 金鑰衍生機制:使用 SHA-256 從密碼衍生金鑰,增強了密碼的安全性。
- 隨機初始向量:每次加密都使用新的隨機 IV,提高了加密的安全性。
- 區塊填充處理:正確實作了 PKCS7 填充,確保資料完整性。
- 錯誤處理:雖然沒有顯示錯誤處理,但程式碼結構允許輕易加入例外處理機制。
最佳實踐建議
- 增強密碼強度檢查:加入密碼強度檢查機制,強制使用者使用複雜密碼。
- 新增例外處理:在檔案操作和加密過程中加入適當的例外處理。
- 考慮加入驗證機制:在加密檔案中加入 HMAC 或其他驗證機制,確保資料完整性。
深入解析 Python 加密技術:安全金鑰生成與對稱加密實務
在資訊安全日益重要的今天,資料加密與解密技術扮演著至關重要的角色。本文將探討 Python 中兩個常用的加密解密技術:PBKDF2 金鑰衍生函式與 AES 對稱加密演算法,並透過實際程式碼範例示範如何運用這些技術保護敏感資料。
PBKDF2:安全金鑰衍生技術
PBKDF2 (Password-Based Key Derivation Function 2) 是一種從密碼衍生加密金鑰的技術,廣泛應用於金鑰管理系統。以下程式碼片段示範如何使用 PBKDF2 從密碼生成金鑰:
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
from cryptography.hazmat.backends import default_backend
import os
import base64
def derive_key(password, salt=None):
if salt is None:
salt = os.urandom(16)
kdf = PBKDF2HMAC(
algorithm=hashes.SHA256(),
length=32,
salt=salt,
iterations=100000,
backend=default_backend()
)
key = kdf.derive(password.encode())
return key, salt
password = "secure_password"
key, salt = derive_key(password)
print(f"Derived Key: {base64.b64encode(key).decode()}")
print(f"Salt: {base64.b64encode(salt).decode()}")
內容解密:
這段程式碼使用 PBKDF2HMAC 類別從給定的密碼和鹽值衍生出金鑰。鹽值(salt)用於增加金鑰衍生的複雜度,防止彩虹表攻擊。iterations 引數設為 100000,以提高運算成本,增加暴力破解的難度。最終輸出金鑰和鹽值的 Base64 編碼結果。
AES 對稱加密實務
AES(Advanced Encryption Standard)是一種高效的對稱加密演算法,廣泛應用於資料加密。以下程式碼示範如何使用 AES-GCM 模式進行加密和解密:
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.backends import default_backend
import os
def encrypt_data(key, data):
iv = os.urandom(12) # GCM 模式推薦使用 96 位元 IV
cipher = Cipher(algorithms.AES(key), modes.GCM(iv), backend=default_backend())
encryptor = cipher.encryptor()
ciphertext = encryptor.update(data.encode()) + encryptor.finalize()
return iv + encryptor.tag + ciphertext
def decrypt_data(key, encrypted_data):
iv = encrypted_data[:12]
tag = encrypted_data[12:28]
ciphertext = encrypted_data[28:]
cipher = Cipher(algorithms.AES(key), modes.GCM(iv, tag), backend=default_backend())
decryptor = cipher.decryptor()
return decryptor.update(ciphertext) + decryptor.finalize()
# 使用 PBKDF2 衍生的金鑰
password = "secure_password"
key, _ = derive_key(password)
data = "這是需要加密的敏感資訊"
encrypted_data = encrypt_data(key, data)
decrypted_data = decrypt_data(key, encrypted_data).decode()
print(f"原始資料: {data}")
print(f"解密資料: {decrypted_data}")
內容解密:
這段程式碼首先使用 AES-GCM 模式進行資料加密。GCM 模式提供了認證功能,能夠檢測資料是否被篡改。加密過程中生成隨機 IV(初始化向量),並將 IV、認證標籤(tag)和密鑰拼接在一起儲存。解密時則根據這些資訊還原始資料。
加密流程示意
流程解密
此圖表展示了從原始資料到最終還原的完整加密解密流程。首先透過 PBKDF2 衍生出金鑰,接著使用 AES-GCM 進行加密,最後再解密還原資料。整個流程強調了金鑰管理和安全引數的重要性。
密碼學基礎與Python實作
在現代網路安全領域,密碼學扮演著至關重要的角色。本文將探討Python中實作密碼學技術的方法,重點介紹對稱加密、非對稱加密以及安全金鑰生成的最佳實踐。
對稱加密技術實作
cryptography 函式庫中的 ciphers 套件提供了實作對稱加密的核心功能。透過 Cipher 類別,開發者可以輕鬆結合加密演算法(如AES)與操作模式(如CBC或CTR)。
AES加密範例
import os
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.backends import default_backend
# 初始化後端與金鑰引數
backend = default_backend()
key = os.urandom(32) # 256位元金鑰
iv = os.urandom(16) # 初始化向量
# 建立AES-CBC加密器
cipher = Cipher(algorithms.AES(key), modes.CBC(iv), backend=backend)
encryptor = cipher.encryptor()
# 加密處理
message = "a secret message".encode("utf8")
message_encrypted = encryptor.update(message)
cipher_text = message_encrypted + encryptor.finalize()
# 解密處理
decryptor = cipher.decryptor()
plain_text = decryptor.update(cipher_text) + decryptor.finalize()
print("解密後的明文:", plain_text.decode())
內容解密:
本範例展示了使用AES-256-CBC模式進行資料加密與解密的完整流程。程式碼中:
- 使用
os.urandom生成安全的金鑰和初始化向量 - 透過
Cipher類別建立加密器和解密器 - 使用
encryptor.update()和encryptor.finalize()完成加密 - 使用
decryptor.update()和decryptor.finalize()完成解密
非對稱加密技術實作
非對稱加密使用公鑰和私鑰對,實作更安全的金鑰交換和數字簽章功能。
RSA加密範例
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.asymmetric import padding
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.backends import default_backend
# 載入金鑰
with open('private_key.pem', 'rb') as f:
private_key = serialization.load_pem_private_key(
f.read(), password=None, backend=default_backend()
)
with open('public_key.pem', 'rb') as f:
public_key = serialization.load_pem_public_key(
f.read(), backend=default_backend()
)
# 加密與解密
plaintext = b'a secret message'
padding_config = padding.OAEP(
mgf=padding.MGF1(algorithm=hashes.SHA256()),
algorithm=hashes.SHA256(),
label=None
)
ciphertext = public_key.encrypt(plaintext, padding_config)
decrypted_text = private_key.decrypt(ciphertext, padding_config)
print("解密結果:", decrypted_text.decode())
內容解密:
此範例演示了使用RSA演算法進行資料加密和解密的過程。主要特點包括:
- 使用OAEP填充方案增強安全性
- 採用SHA256作為雜湊演算法
- 透過PEM格式載入金鑰
安全金鑰生成技術
secrets 模組提供了一種安全生成隨機數的方法,特別適用於密碼、驗證令牌等敏感資訊的生成。
安全密碼生成範例
import secrets
import string
# 定義字元集
characters = string.ascii_letters + string.digits
length = 16
# 生成安全密碼
password = ''.join(secrets.choice(characters) for _ in range(length))
print("生成的密碼:", password)
內容解密:
本範例展示瞭如何使用secrets模組生成高強度的隨機密碼。主要特點包括:
- 使用密碼學安全的亂數生成器
- 結合大小寫字母和數字字元
- 可自訂密碼長度
流程視覺化
流程說明: 此圖展示了使用PBKDF2派生金鑰並進行AES加密/解密的完整流程。
@startuml
skinparam backgroundColor #FEFEFE
skinparam componentStyle rectangle
title Python加密解密技術實務
package "安全架構" {
package "網路安全" {
component [防火牆] as firewall
component [WAF] as waf
component [DDoS 防護] as ddos
}
package "身份認證" {
component [OAuth 2.0] as oauth
component [JWT Token] as jwt
component [MFA] as mfa
}
package "資料安全" {
component [加密傳輸 TLS] as tls
component [資料加密] as encrypt
component [金鑰管理] as kms
}
package "監控審計" {
component [日誌收集] as log
component [威脅偵測] as threat
component [合規審計] as audit
}
}
firewall --> waf : 過濾流量
waf --> oauth : 驗證身份
oauth --> jwt : 簽發憑證
jwt --> tls : 加密傳輸
tls --> encrypt : 資料保護
log --> threat : 異常分析
threat --> audit : 報告生成
@enduml
流程說明: 本圖詳細展示了AES對稱加密的運作原理,包括金鑰在加解密過程中的作用。