【发布时间】:2020-03-10 09:07:48
【问题描述】:
早安,
我正在做密码学作业。这是一项简单的任务,我需要拍摄任何图像,将其转换为 HEX,加密然后解密。
由于我在 Python 中工作,并且任务中没有特定的加密方法,所以我只使用了 Fernet。
我有一个加密器和解密器脚本。
加密似乎有效,因为作为测试,我使用原始 HEX 创建了一个 txt 文档,解密后程序指出原始 HEX 和解密后的文件相同,但未加载解密图像。
有人能帮帮新手吗?
加密器:
import binascii
from cryptography.fernet import Fernet
img = 'panda.png'
with open(img, 'rb') as f:
content = f.read()
hexValue = binascii.hexlify(content)
key = Fernet.generate_key()
with open('info/key.txt', mode='w+') as keyValue:
keyValue.write(key)
keyValue.seek(0)
f = Fernet(key)
encHexVal = f.encrypt(hexValue)
with open('info/encryptedHex.txt', mode='w+') as hexValueFile:
hexValueFile.write(encHexVal)
hexValueFile.seek(0)
a = f.decrypt(encHexVal)
with open('info/realValue.txt', mode='w+') as writeHex:
originalHex = writeHex.write(hexValue)
with open('info/realValue.txt', mode='r') as reading:
realValue = reading.read()
if realValue == a:
print("We're good to go!")
else:
print("Oops something went wrong. Check the source code.")
解密器:
import binascii
from cryptography.fernet import Fernet
with open('info/key.txt', mode='rb') as keyValue:
key = keyValue.read()
f = Fernet(key)
with open('info/encryptedHex.txt', mode='rb') as imageHexValue:
hexValue = imageHexValue.read()
a = f.decrypt(hexValue)
with open('info/realValue.txt', mode='r') as compare:
realContents = compare.read()
print("Small test in safe environment...")
if realContents == a:
print("All good!")
else:
print("Something is wrong...")
data = a.encode()
data = data.strip()
data = data.replace(' ', '')
data = data.replace('\n', '')
with open('newImage.png', 'wb') as file:
file.write(data)
【问题讨论】:
-
Encrypter 中,open('info/key.txt', mode='w+') 错误...需要以二进制模式打开。
-
是不是应该先加密再转HEX?换一种方式,你会得到二进制,而不是文本。
-
你用的是哪个版本的python?代码中有几个字节/字符串问题。
-
@tdelaney 我通过写“wb+”来修复它,但图像仍然没有加载。我使用的是python 3。它应该首先将其转换为HEX,然后对HEX值本身进行加密。
-
在这种情况下,'info/encryptedHex.txt' 是真正的二进制。核心问题是你没有在保存 newImage.png 之前 unhexlify 解密的数据。
标签: python image encryption cryptography