```python from Crypto.PublicKey import RSA from Crypto.Cipher import PKCS1_OAEP from Crypto.Hash import SHA256 from Crypto.Cipher import AES from Crypto.Random import get_random_bytes from Crypto import Random from Crypto.Util.Padding import pad, unpad from PIL import Image def encrypt_image(input_image_path, output_image_path, key_size=2048): key = RSA.generate(key_size) public_key = key.publickey().export_key() cipher_rsa = PKCS1_OAEP.new(RSA.import_key(public_key)) with open(input_image_path, 'rb') as f: image_data = f.read() session_key = get_random_bytes(16) cipher_aes = AES.new(session_key, AES.MODE_CBC) encrypted_session_key = cipher_rsa.encrypt(session_key) cipher_text = cipher_aes.encrypt(pad(image_data, AES.block_size)) with open(output_image_path, 'wb') as f: f.write(public_key + encrypted_session_key + cipher_text) def decrypt_image(input_image_path, output_image_path): with open(input_image_path, 'rb') as f: private_key = RSA.import_key(f.read(2048)) encrypted_data = f.read() session_key = private_key.decrypt(encrypted_data[:private_key.size_in_bytes()]) cipher_aes = AES.new(session_key, AES.MODE_CBC) decrypted_data = unpad(cipher_aes.decrypt(encrypted_data[private_key.size_in_bytes():]), AES.block_size) with open(output_image_path, 'wb') as f: f.write(decrypted_data) input_image_path = 'input.jpg' encrypted_image_path = 'encrypted_image.jpg' decrypted_image_path = 'decrypted_image.jpg' encrypt_image(input_image_path, encrypted_image_path) decrypt_image(encrypted_image_path, decrypted_image_path) ``` 注意事项: 1. 确保安全存储和管理 RSA 私钥,不要泄露给他人。 2. 对于大型图片,考虑对图片进行分块处理以加快加密和解密过程。 3. 在处理图片时,建议使用合适的填充方式以避免数据被截取或损坏。 [2025-01-05 18:37:09 | AI写代码神器 | 1269点数解答]