今天为大家介绍一个在 Python 中用于加密和解密操作的库——cryptography,它提供了多种加密算法和工具,帮助开发者实现数据保护、身份验证和加密通信等功能。该库涵盖了对称加密、非对称加密、哈希算法、消息认证码(MAC)等基本加密技术,适用于各种安全应用场景。要使用 cryptography 库,首先需要安装它。可以通过以下命令安装:pip install cryptography
cryptography 提供了多种模式(如 CBC、GCM 等)。from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import padding
import os
key = os.urandom(32)
iv = os.urandom(16)
cipher = Cipher(algorithms.AES(key), modes.CBC(iv), backend=default_backend())
encryptor = cipher.encryptor()
data = b"Hello, World!"
padder = padding.PKCS7(128).padder()
padded_data = padder.update(data) + padder.finalize()
ciphertext = encryptor.update(padded_data) + encryptor.finalize()
print(f"Ciphertext: {ciphertext}")
非对称加密使用一对公钥和私钥。常用于数字签名和安全密钥交换。from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.asymmetric import padding
private_key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
public_key = private_key.public_key()
message = b"Encrypt this message"
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(f"Decrypted message: {plaintext}")
哈希算法通常用于验证数据完整性。SHA-256 是一种常见的哈希算法。from cryptography.hazmat.primitives import hashes
digest = hashes.Hash(hashes.SHA256())
data = b"Hello, World!"
digest.update(data)
hash_value = digest.finalize()
print(f"SHA-256 Hash: {hash_value.hex()}")
Fernet 是一个提供安全对称加密的方案,它简化了密钥管理,内置了加密和认证功能。from cryptography.fernet import Fernet
key = Fernet.generate_key()
cipher = Fernet(key)
data = b"Secret message"
ciphertext = cipher.encrypt(data)
plaintext = cipher.decrypt(ciphertext)
print(f"Decrypted message: {plaintext.decode()}")
ECDSA 是一种基于椭圆曲线密码学的数字签名算法,提供了更高效的签名生成和验证方法。from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.asymmetric import ec
private_key = ec.generate_private_key(ec.SECP256R1(), default_backend())
public_key = private_key.public_key()
message = b"Important message"
signature = private_key.sign(message, hashes.SHA256())
try:
public_key.verify(signature, message, hashes.SHA256())
print("Signature is valid!")
except Exception as e:
print(f"Signature verification failed: {e}")
将文件加密存储,并通过安全的方式进行解密,确保数据隐私。def encrypt_file(file_path, key):
cipher = Fernet(key)
with open(file_path, "rb") as file:
data = file.read()
encrypted_data = cipher.encrypt(data)
with open(file_path + ".enc", "wb") as enc_file:
enc_file.write(encrypted_data)
def decrypt_file(file_path, key):
cipher = Fernet(key)
with open(file_path, "rb") as enc_file:
encrypted_data = enc_file.read()
decrypted_data = cipher.decrypt(encrypted_data)
with open(file_path.replace(".enc", ".dec"), "wb") as dec_file:
dec_file.write(decrypted_data)
使用哈希和盐值(Salt)技术来安全存储用户密码。from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
import os
def hash_password(password):
salt = os.urandom(16)
kdf = PBKDF2HMAC(
algorithm=hashes.SHA256(),
length=32,
salt=salt,
iterations=100000
)
hashed_password = kdf.derive(password.encode())
return salt + hashed_password
def verify_password(stored_password, password):
salt = stored_password[:16]
stored_hash = stored_password[16:]
kdf = PBKDF2HMAC(
algorithm=hashes.SHA256(),
length=32,
salt=salt,
iterations=100000
)
kdf.verify(password.encode(), stored_hash)
cryptography 库为 Python 提供了强大的加密支持,涵盖了对称加密、非对称加密、哈希、签名、消息认证码等基本加密技术。它既有高层接口,便于快速集成,又有低层接口,适合需要更高控制的场景。随着安全性需求的提升,cryptography 是开发安全应用不可或缺的工具之一。本文详细介绍了 cryptography 库的安装方法、基本用法和高级功能,以及实际应用场景。
希望通过本文大家能够全面了解和熟练使用 cryptography 库,在实际项目中充分发挥其优势。今天的 Python 学习之旅就到这里啦!记得多多实践哦~有任何问题,随时在评论区留言。