1、理解
加密是通过使用各种加密算法来对数据进行加密和解密的过程。Python 提供了许多内置库和第三方库,可以用于实现各种加密算法和技术,包括对称加密、非对称加密、哈希函数等。以下是 Python 中常用的一些加密相关的库和模块:
2、对称加密和非对称加密
对称加密和非对称加密是两种常见的加密算法,它们在加密和解密数据时使用不同的密钥管理方式。
对称加密:
from Crypto.Cipher import AES
from Crypto.Random import get_random_bytes
# 生成随机密钥
key = get_random_bytes(16)
# 要加密的数据
data = b"Hello, World!"
# 创建 AES 加密对象
cipher = AES.new(key, AES.MODE_EAX)
# 加密数据
ciphertext, tag = cipher.encrypt_and_digest(data)
print("加密后的数据:", ciphertext)
# 解密数据
cipher = AES.new(key, AES.MODE_EAX, cipher.nonce)
decrypted_data = cipher.decrypt_and_verify(ciphertext, tag)
print("解密后的数据:", decrypted_data.decode('utf-8'))
非对称加密:
from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import padding
from cryptography.hazmat.primitives import hashes
# 生成 RSA 密钥对
private_key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
public_key = private_key.public_key()
# 加密数据
data = b"Hello, World!"
ciphertext = public_key.encrypt(data, padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA256()), algorithm=hashes.SHA256(), label=None))
print("加密后的数据:", ciphertext)
# 解密数据
decrypted_data = private_key.decrypt(ciphertext, padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA256()), algorithm=hashes.SHA256(), label=None))
print("解密后的数据:", decrypted_data.decode('utf-8'))
加密和解密算法和方法比较多,在实际应用中,我们需要根据具体的安全需求和情景来选择合适的加密算法和方法。