赞
踩
下面是使用 Python 实现 AES 加密和解密的示例代码:
- import base64
- import hashlib
- import os
- from cryptography.hazmat.backends import default_backend
- from cryptography.hazmat.primitives import padding, serialization
- from cryptography.hazmat.primitives.ciphers import (
- Cipher, algorithms, modes
- )
-
-
- def generate_key(password: str, salt: bytes, iterations: int = 100000, key_size: int = 32):
- kdf = hashlib.pbkdf2_hmac('sha256', password.encode(), salt, iterations, key_size)
- return kdf
-
-
- def encrypt(plaintext: str, password: str, salt: bytes):
- # Generate key
- key = generate_key(password, salt)
-
- # Add padding to the plaintext
- padder = padding.PKCS7(algorithms.AES.block_size).padder()
- padded_plaintext = padder.update(plaintext.encode()) + padder.finalize()
-
- # Generate a random IV
- iv = os.urandom(16)
-
- # Encrypt the plaintext
- cipher = Cipher(algorithms.AES(key), modes.CBC(iv), backend=default_backend())
- encryptor = cipher.encryptor()
- ciphertext = encryptor.update(padded_plaintext) + encryptor.finalize()
-
- # Concatenate the IV and the ciphertext
- encrypted_message = iv + ciphertext
-
- # Encode the encrypted message as a base64 string
- encoded_encrypted_message = base64.b64encode(encrypted_message)
-
- return encoded_encrypted_message
-
-
- def decrypt(encoded_encrypted_message: str, password: str, salt: bytes):
- # Decode the encrypted message from a base64 string
- encrypted_message = base64.b64decode(encoded_encrypted_message)
-
- # Split the IV and the ciphertext
- iv = encrypted_message[:16]
- ciphertext = encrypted_message[16:]
-
- # Generate key
- key = generate_key(password, salt)
-
- # Decrypt the ciphertext
- cipher = Cipher(algorithms.AES(key), modes.CBC(iv), backend=default_backend())
- decryptor = cipher.decryptor()
- padded_plaintext = decryptor.update(ciphertext) + decryptor.finalize()
-
- # Remove padding from the plaintext
- unpadder = padding.PKCS7(algorithms.AES.block_size).unpadder()
- plaintext = unpadder.update(padded_plaintext) + unpadder.finalize()
-
- return plaintext.decode()
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。