共計 924 個字符,預計需要花費 3 分鐘才能閱讀完成。
在 Python 中,常用的數據加密和解密方法有以下幾種:
- hashlib 模塊:使用哈希算法加密數據,常用的哈希算法有 MD5、SHA1、SHA256 等。可以使用 hashlib 庫中的各種哈希算法函數對數據進行加密和解密。
示例代碼:
import hashlib
# 加密數據
data = "Hello World"
hashed_data = hashlib.sha256(data.encode()).hexdigest()
print(hashed_data)
# 解密數據
# 由于哈希算法是單向的,無法逆向解密,只能通過對比哈希值來驗證數據的一致性
- base64 模塊:將數據進行 Base64 編碼和解碼。Base64 編碼是一種將二進制數據轉換為可打印 ASCII 字符的編碼方式,常用于在網絡傳輸中傳遞二進制數據。
示例代碼:
import base64
# 加密數據
data = "Hello World"
encoded_data = base64.b64encode(data.encode()).decode()
print(encoded_data)
# 解密數據
decoded_data = base64.b64decode(encoded_data).decode()
print(decoded_data)
- cryptography 庫:一個功能強大的加密和解密庫,提供了對稱加密、非對稱加密和哈希算法等多種加密算法。
示例代碼:
from cryptography.fernet import Fernet
# 生成密鑰
key = Fernet.generate_key()
# 加密數據
cipher_suite = Fernet(key)
data = "Hello World"
encrypted_data = cipher_suite.encrypt(data.encode()).decode()
print(encrypted_data)
# 解密數據
decrypted_data = cipher_suite.decrypt(encrypted_data.encode()).decode()
print(decrypted_data)
以上是 Python 中常用的數據加密和解密方法,具體的選擇取決于需求和場景。
丸趣 TV 網 – 提供最優質的資源集合!
正文完