如何利用Key()在python中实现图片加密和解密
发布时间:2023-12-15 02:53:43
在Python中使用Key()实现图片加密和解密可以采用对称加密算法,其中Key()函数可以用于生成加密和解密所需的密钥。下面是一个实现图片加密和解密的示例代码,包括生成密钥、图片加密和解密的函数:
import os
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.backends import default_backend
def generate_key():
key = os.urandom(32)
return key
def encrypt_image(key, image_path, encrypted_image_path):
with open(image_path, 'rb') as image_file:
image = image_file.read()
iv = os.urandom(16)
cipher = Cipher(algorithms.AES(key), modes.CFB(iv), backend=default_backend())
encryptor = cipher.encryptor()
encrypted_image = encryptor.update(image) + encryptor.finalize()
with open(encrypted_image_path, 'wb') as encrypted_image_file:
encrypted_image_file.write(iv + encrypted_image)
def decrypt_image(key, encrypted_image_path, decrypted_image_path):
with open(encrypted_image_path, 'rb') as encrypted_image_file:
encrypted_image = encrypted_image_file.read()
iv = encrypted_image[:16]
encrypted_image = encrypted_image[16:]
cipher = Cipher(algorithms.AES(key), modes.CFB(iv), backend=default_backend())
decryptor = cipher.decryptor()
decrypted_image = decryptor.update(encrypted_image) + decryptor.finalize()
with open(decrypted_image_path, 'wb') as decrypted_image_file:
decrypted_image_file.write(decrypted_image)
在上述代码中,generate_key()函数用于生成一个随机的32字节的密钥。encrypt_image()函数将指定路径的图片进行加密,并将加密后的图片保存到指定路径。decrypt_image()函数将指定路径的加密图片进行解密,并将解密后的图片保存到指定路径。
下面是一个使用上述代码的示例:
key = generate_key() image_path = 'image.jpg' encrypted_image_path = 'encrypted_image.jpg' decrypted_image_path = 'decrypted_image.jpg' encrypt_image(key, image_path, encrypted_image_path) decrypt_image(key, encrypted_image_path, decrypted_image_path)
在示例中,首先通过generate_key()函数生成一个密钥。然后,将要加密的图片'image.jpg'传入encrypt_image()函数进行加密,加密后的图片保存到'encrypted_image.jpg'。接着,调用decrypt_image()函数对加密后的图片进行解密,解密后的图片保存到'decrypted_image.jpg'。
需要注意的是,示例代码中使用了AES算法和CFB模式进行加密和解密。在实际应用中,可能需要根据具体的需求选择合适的加密算法和模式。
