# Python加密算法怎么使用
在現代信息安全領域,加密算法是保護數據隱私和完整性的核心技術。Python憑借其豐富的庫生態,成為實現加密算法的熱門工具。本文將詳細介紹Python中常用加密算法的使用方法,包含對稱加密、非對稱加密和哈希算法三類典型場景。
---
## 一、加密算法基礎分類
### 1. 對稱加密
使用相同密鑰進行加密/解密,速度快但需安全傳輸密鑰
- 典型算法:AES, DES, 3DES
- 適用場景:大數據量加密(如文件加密)
### 2. 非對稱加密
使用公鑰/私鑰對,安全性高但計算復雜
- 典型算法:RSA, ECC
- 適用場景:密鑰交換、數字簽名
### 3. 哈希算法
單向不可逆的摘要算法
- 典型算法:SHA-256, MD5
- 適用場景:密碼存儲、數據完整性校驗
---
## 二、Python實現對稱加密(AES示例)
### 安裝依賴庫
```bash
pip install pycryptodome
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad, unpad
from Crypto.Random import get_random_bytes
key = get_random_bytes(16) # 生成128位密鑰
iv = get_random_bytes(16) # 初始化向量
# 加密
cipher = AES.new(key, AES.MODE_CBC, iv)
plaintext = b"Secret message"
ciphertext = cipher.encrypt(pad(plaintext, AES.block_size))
# 解密
cipher = AES.new(key, AES.MODE_CBC, iv)
decrypted = unpad(cipher.decrypt(ciphertext), AES.block_size)
print(decrypted) # b'Secret message'
pip install cryptography
from cryptography.hazmat.primitives.asymmetric import rsa, padding
from cryptography.hazmat.primitives import serialization, hashes
# 生成密鑰對
private_key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
public_key = private_key.public_key()
# 公鑰加密
message = b"Confidential data"
ciphertext = public_key.encrypt(
message,
padding.OAEP(
mgf=padding.MGF1(algorithm=hashes.SHA256()),
algorithm=hashes.SHA256(),
label=None
)
)
# 私鑰解密
plaintext = private_key.decrypt(
ciphertext,
padding.OAEP(
mgf=padding.MGF1(algorithm=hashes.SHA256()),
algorithm=hashes.SHA256(),
label=None
)
)
print(plaintext) # b'Confidential data'
import hashlib
# 計算哈希值
message = "Password123".encode('utf-8')
hash_obj = hashlib.sha256(message)
hex_dig = hash_obj.hexdigest()
print(hex_dig) # 64字符的十六進制字符串
import os
import hashlib
def hash_password(password):
salt = os.urandom(32) # 隨機鹽值
key = hashlib.pbkdf2_hmac(
'sha256',
password.encode('utf-8'),
salt,
100000 # 迭代次數
)
return salt + key
# 驗證密碼
def verify_password(stored, password):
salt = stored[:32]
stored_key = stored[32:]
new_key = hashlib.pbkdf2_hmac(
'sha256',
password.encode('utf-8'),
salt,
100000
)
return new_key == stored_key
密鑰管理
算法選擇
實踐建議
官方文檔:
安全標準參考:
通過本文介紹的Python加密實現方法,開發者可以快速構建基本的數據安全防護體系。實際應用中還需結合具體業務場景進行安全設計和審計。 “`
注:本文實際約1100字,包含代碼示例、分類說明和安全建議三個核心部分,采用Markdown格式實現標題分級和代碼高亮??筛鶕枰{整具體算法的示例代碼或補充特定應用場景的說明。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。