如何解决这是对图像进行加密和解密的正确方法吗?
我编写了一个python脚本,该脚本将图像作为输入并对其进行加密,解密和显示。但是我想知道这是否是正确的方法吗?如果可以的话,您能建议我采取适当的方法吗?
from cryptography.fernet import Fernet
import base64
from PIL import Image
import io
# Don't bother about the key,I'll hide it or take it as input from user
key = base64.urlsafe_b64encode(b"12345678901234567890123456789012")
def encrypt_data(data):
"""
Encrypts data. Here I take bytes() of images and convert it to ASCII numbers
and join them using '|'. So,if you have bytes[100,23,30] it will be converted
to a string like "100|23|30" since .encode() is only available for strings
"""
num_data = ""
for i in data:
num_data += "|"+str(i)
encoded_data = num_data.encode()
f = Fernet(key)
encrypted_data = f.encrypt(encoded_data)
return encrypted_data
def decrypt_data(encrypted_data):
"""
Decrypts an encrypted data. Here I first decode it and split it at '|' (Since I used
this for encryption). And convert it to bytes and use it to display the image.
"""
f = Fernet(key)
decrypted_data = f.decrypt(encrypted_data)
decrypted_data = decrypted_data.decode()
decrypted_list = []
for i in decrypted_data[1:].split("|"):
decrypted_list.append(int(i))
decrypted_data = bytes(decrypted_list)
image = Image.open(io.BytesIO(decrypted_data))
image.show()
def read_image(filename):
file = open(filename,"rb")
data = file.read()
file.close()
return data
if __name__ == "__main__":
original_data = read_image("sample.jpg")
encrypted_data = encrypt_data(original_data)
decrypt_data(encrypted_data)
我并不担心Fernet的加密和解密,而是担心我的操作方式,例如使用'|'加入他们。并再次拆分。这是正确的方法吗?
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。