cryptography.hazmat.primitives.serialization模块中支持的加密算法介绍
发布时间:2024-01-15 01:40:20
cryptography.hazmat.primitives.serialization模块是Python的一个加密库,提供了各种加密算法的功能。在这里,我将介绍一些主要的加密算法并提供使用例子。
1. AES (Advanced Encryption Standard)
AES是一种对称加密算法,以块的方式加密数据。它支持多种密钥长度,包括128位、192位和256位。下面是一个使用AES算法加密和解密数据的示例:
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.backends import default_backend
key = b'abcdefghabcdefgh' # AES-128密钥
plaintext = b'Hello, world!' # 明文
# 配置AES算法和ECB模式
cipher = Cipher(algorithms.AES(key), modes.ECB(), backend=default_backend())
# 创建加密器和解密器对象
encryptor = cipher.encryptor()
decryptor = cipher.decryptor()
# 加密数据
ciphertext = encryptor.update(plaintext) + encryptor.finalize()
print("Cipher text:", ciphertext)
# 解密数据
decrypted_text = decryptor.update(ciphertext) + decryptor.finalize()
print("Decrypted text:", decrypted_text)
2. RSA (Rivest-Shamir-Adleman)
RSA是一种非对称加密算法,通过使用公钥和私钥对数据进行加密和解密。以下是一个使用RSA算法生成密钥对、加密和解密数据的示例:
from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.hazmat.primitives import serialization, hashes
from cryptography.hazmat.backends import default_backend
# 生成RSA私钥
private_key = rsa.generate_private_key(
public_exponent=65537,
key_size=2048,
backend=default_backend()
)
# 从私钥生成公钥
public_key = private_key.public_key()
# 序列化私钥和公钥
private_pem = private_key.private_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PrivateFormat.PKCS8,
encryption_algorithm=serialization.NoEncryption()
)
public_pem = public_key.public_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PublicFormat.SubjectPublicKeyInfo
)
# 加密数据
plaintext = b'Hello, world!'
ciphertext = public_key.encrypt(
plaintext,
padding.OAEP(
mgf=padding.MGF1(algorithm=hashes.SHA256()),
algorithm=hashes.SHA256(),
label=None
)
)
print("Cipher text:", ciphertext)
# 解密数据
decrypted_text = private_key.decrypt(
ciphertext,
padding.OAEP(
mgf=padding.MGF1(algorithm=hashes.SHA256()),
algorithm=hashes.SHA256(),
label=None
)
)
print("Decrypted text:", decrypted_text)
3. HMAC (Hash-based Message Authentication Code)
HMAC是一种使用哈希算法和密钥生成一个固定长度的认证码。它常用于验证数据完整性。以下是一个使用HMAC算法生成和验证认证码的示例:
from cryptography.hazmat.primitives import hashes, hmac
from cryptography.hazmat.backends import default_backend
key = b'secret_key' # 密钥
message = b'Hello, world!' # 消息
# 创建HMAC对象
h = hmac.HMAC(key, hashes.SHA256(), backend=default_backend())
# 生成认证码
h.update(message)
digest = h.finalize()
print("Digest:", digest)
# 验证认证码
h.verify(digest) # 如果认证码验证通过,不会抛出异常
这些是cryptography.hazmat.primitives.serialization模块中支持的一些加密算法。使用这些算法可以保护数据的机密性、完整性和认证性,使其更安全地在网络上传输。
