Python3 - шифрование и дешифрование изображения (например, rnet). - PullRequest
0 голосов
/ 10 марта 2020

Добрый день,

Я выполняю задание по криптографии. Это простая задача, мне нужно взять любое изображение, превратить его в HEX, зашифровать, а затем расшифровать.

Поскольку я работаю в Python, и в задаче не было определенного метода шифрования c Я просто использую Fe rnet.

У меня есть сценарии шифрования и расшифровки.

Шифрование работает, потому что в качестве теста я создаю текстовый документ с оригинальным HEX, и после дешифрования программа сообщает, что исходный HEX и дешифрованный один совпадают, однако дешифрованное изображение не загружается.

Может ли кто-нибудь выручить новичка ie?

Encryptor:

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.")

Decryptor:

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)

Я использую случайное изображение из inte rnet по из Кунг-фу Панды: Po from Kung Fu Panda

1 Ответ

2 голосов
/ 10 марта 2020

Принципиальная проблема заключается в том, что, хотя вы шифруете, а затем шифруете в шифраторе, вы не освобождаете его от расшифровки в расшифровщике. Гораздо чаще можно поступить иначе, зашифровав, а затем зашифровав, чтобы зашифрованный двоичный файл можно было сохранить в обычных текстовых файлах или отправить по http.

У вас есть несколько проблем при попытке записи bytes объектов в файлы, открытые в текстовом формате. Я исправил это по пути. Но меня это озадачивает, почему файл с именем info / encryptedHex.txt будет двоичным.

Encryptor

import binascii
from cryptography.fernet import Fernet

# Generate keyfile
#
# TODO: Overwrites key file on each run, invalidating previous
# saves. You could do `if not os.path.exists('info/key.txt'):`
key = Fernet.generate_key()
with open('info/key.txt', mode='wb') as keyValue:
    keyValue.write(key)

# Encrypt image
img = 'panda.png'
with open(img, 'rb') as f:
    content = f.read()
hexValue = binascii.hexlify(content)

f = Fernet(key)
encHexVal = f.encrypt(hexValue) 

with open('info/encryptedHex.txt', mode='wb') as hexValueFile:
    hexValueFile.write(encHexVal)

# Verification checks
a = f.decrypt(encHexVal)

# hexed bytes is same encoding as 'ascii'
with open('info/realValue.txt', mode='wb') as writeHex:
    originalHex = writeHex.write(hexValue)

with open('info/realValue.txt', mode='r', encoding='ascii') as reading:
    realValue = reading.read()
if realValue == a.decode('ascii'):
    print("We're good to go!")
else:
    print("Oops something went wrong. Check the source code.")

Decryptor

import binascii
from cryptography.fernet import Fernet

# Generate keyfile
#
# TODO: Overwrites key file on each run, invalidating previous
# saves. You could do `if not os.path.exists('info/key.txt'):`
key = Fernet.generate_key()
with open('info/key.txt', mode='wb') as keyValue:
    keyValue.write(key)

# Encrypt image
img = 'panda.png'
with open(img, 'rb') as f:
    content = f.read()
hexValue = binascii.hexlify(content)

f = Fernet(key)
encHexVal = f.encrypt(hexValue) 

with open('info/encryptedHex.txt', mode='wb') as hexValueFile:
    hexValueFile.write(encHexVal)

# Verification checks
a = f.decrypt(encHexVal)

# hexed bytes is same encoding as 'ascii'
with open('info/realValue.txt', mode='wb') as writeHex:
    originalHex = writeHex.write(hexValue)

with open('info/realValue.txt', mode='r', encoding='ascii') as reading:
    realValue = reading.read()
if realValue == a.decode('ascii'):
    print("We're good to go!")
else:
    print("Oops something went wrong. Check the source code.")
(base) td@timpad:~/dev/SO/Encrypting and decrypting in image$ cat de.py
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:
    encHexValue = imageHexValue.read()
hexValue = f.decrypt(encHexValue)
binValue = binascii.unhexlify(hexValue)

with open('info/realValue.txt', mode='rb') as compare:
    realContents = compare.read()

print("Small test in safe environment...")
if realContents == hexValue:
    print("All good!")
else:
    print("Something is wrong...")
with open('newImage.png', 'wb') as file:
    file.write(binValue)
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...