Python加密与编码实现
Python加密与编码实现
编解码操作
Base64
import base64
encoded = base64.b64encode(b'hello').decode() # aGVsbG8=
decoded = base64.b64decode(encoded).decode() # helloURL编码
from urllib.parse import quote, unquote
encoded = quote('hello world') # hello%20worldHex编码
hex_str = b'hello'.hex() # 68656c6c6f
raw = bytes.fromhex(hex_str) # b'hello'哈希计算
import hashlib
# MD5
md5 = hashlib.md5(b'hello').hexdigest()
# SHA256
sha256 = hashlib.sha256(b'hello').hexdigest()
# 文件哈希
with open('file.txt', 'rb') as f:
file_hash = hashlib.sha256(f.read()).hexdigest()AES 加密
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.backends import default_backend
key = b'0123456789abcdef'
iv = b'abcdef0123456789'
cipher = Cipher(algorithms.AES(key), modes.CBC(iv), backend=default_backend())总结
Python 的加密和编码能力覆盖了安全领域的大部分需求。使用 cryptography 库可以获得工业级的加密实现。