Шифрование текста в картинке bmp
17.02.2024, 08:06. Показов 485. Ответов 0
Здравствуйте. У меня такая задача: с помощью winforms прочитать текст с файла и изображение bmp. Затем зашифровать символы из файла в изображение. В программе (код предоставлю ниже) 2 проблемы:
1. Программа работает только если указать название файла явно в коде. Считывать его с textBox не получается, вернее получается считать, но не использовать. Все ломается в методах ReadFile и SafeOpen.
2. При нажатии на кнопку выполнить появляется окно с сообщением:
"Debug Assertion Failed!
Program: ...x64\Debug\textEncryption.exe
File: ...exec\system.cpp
Line 43
Expression: command[0] != '\0'
For information on how your program can cause an assertion
failure, see the Visual C++ documentation on asserts.
(Press Retry to debug the application)
"
Далее программа тормозит на методах ReadFile и SafeOpen.
| C++ | 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
| //enCoder.cpp
#include "enCoder.h"
textEncryption::enCoder::enCoder(void) { InitializeComponent(); }
textEncryption::enCoder::~enCoder()
{
if (components) { delete components; }
}
void textEncryption::enCoder::encryptionTextIntoImage(
unsigned char* buffer,
unsigned width,
unsigned height,
unsigned int* inputText,
int countSymbols)
{
srand(time(NULL));
std::ofstream keyFile("Keys.txt");
for (int i = 0; i < countSymbols; i++)
{
int y = 1 + rand() % (width * height); // Выбираем пиксель, к которому будем присваивать значение из InputText
buffer[y] = inputText[i]; // Заносим букву в пиксель
keyFile << y; // Сохраняем ключи
keyFile << " ";
}
keyFile.close();
}
void textEncryption::enCoder::SafeOpen(FILE*& f, const char* name, const char* mode) { fopen_s(&f, name, mode); }
unsigned char* textEncryption::enCoder::ReadFile(const char* name, unsigned char* header)
{
FILE* in;
unsigned char* buffer;
unsigned int width, height;
SafeOpen(in, name, "rb");
fread(header, 1, 54, in); // Заносим в хедер всю информацию о файле картинки
width = *(unsigned int*)(header + 18);
height = *(unsigned int*)(header + 22);
buffer = (unsigned char*)malloc(width * height * 4);
fread (buffer, 1, width * height * 4, in);
fclose(in);
return buffer;
}
void textEncryption::enCoder::SaveFile(const char* name,
unsigned char* header,
unsigned char* buffer,
unsigned int len)
{
FILE* out;
SafeOpen(out, name, "wb");
fwrite(header, 1, 54, out);
fwrite(buffer, 1, len, out);
fclose(out);
}
System::Void textEncryption::enCoder::start_btn_Click(System::Object^ sender, System::EventArgs^ e)
{
char _char; // Переменная, куда будем записывать символы из файла
int countSymbols = 0; // Число символов в файле
String^ pathToTxt = this->path_to_txt ->Text;
String^ pathToImage = this->path_to_image->Text;
// Преобразуем System::String^ в const char* чтобы использовать с ifstream
msclr::interop::marshal_context ctx;
const char* convertedPathToTxt = ctx.marshal_as<const char*>(pathToTxt);
system(convertedPathToTxt);
std::ifstream file;
file.open(convertedPathToTxt);
while (file.get(_char)) { countSymbols++; } // Считаем количество символов в текстовом файле
file.close();
std::ifstream file2;
file2.open(convertedPathToTxt);
unsigned int* inputText; // Массив для хранения Ascii кодов из файла
inputText = new unsigned int[countSymbols];
int i = 0;
while (file2.get(_char))
{
inputText[i] = _char;
i++;
}
file2.close();
unsigned char* buffer_original, * bufferCPP;
unsigned int width, height, len;
unsigned char headers[54];
const char* convertedPathToImage = ctx.marshal_as<const char*>(pathToImage);
system(convertedPathToImage);
buffer_original = ReadFile(convertedPathToImage, headers); // headers – информация о изображении
width = *(unsigned int*)(headers + 18); // сдвиг 18 информация о ширине
height = *(unsigned int*)(headers + 22); // сдвиг 22 информация о высоте
len = width * height * 4;
bufferCPP = (unsigned char*)malloc(len);
memcpy(bufferCPP, buffer_original, len); // копируем len байтов из buffer_original в bufferCPP
encryptionTextIntoImage(bufferCPP, width, height, inputText, countSymbols); // Шифруем текст в картинку
SaveFile("encryptionFile.bmp", headers, bufferCPP, len); // Сохраняем картинку в CPP.bmp
free(bufferCPP);
free(buffer_original);
delete[] inputText;
} |
|
| C++ | 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
| //enCoder.h
#pragma once
#include <iostream>
#include "deCoder.h"
#include <cstddef>
#include <fstream>
#include <ctime>
#include <msclr/marshal.h>
namespace textEncryption {
using namespace System;
using namespace System::ComponentModel;
using namespace System::Collections;
using namespace System::Windows::Forms;
using namespace System::Data;
using namespace System::Drawing;
using namespace System::Runtime::InteropServices;
/// <summary>
/// Сводка для enCoder
/// </summary>
public ref class enCoder : public System::Windows::Forms::Form
{
public:
enCoder(void);
char* and_SysStringToChar(System::String^ string)
{
return (char*)(void*)Marshal::StringToHGlobalAnsi(string);
}
void encryptionTextIntoImage(
unsigned char* buffer,
unsigned width,
unsigned height,
unsigned int* inputText,
int countSymbols);
void SafeOpen(FILE*& f, const char* name, const char* mode);
unsigned char* ReadFile(const char* name, unsigned char* header);
void SaveFile (const char* name, unsigned char* header, unsigned char* buffer, unsigned int len);
protected:
/// <summary>
/// Освободить все используемые ресурсы.
/// </summary>
~enCoder();
private: System::Windows::Forms::TextBox^ path_to_image;
private: System::Windows::Forms::TextBox^ path_to_txt;
private: System::Windows::Forms::Button^ start_btn;
private: System::Windows::Forms::Button^ back_btn;
private: System::Windows::Forms::Label^ label1;
private: System::Windows::Forms::Label^ label2;
private:
System::ComponentModel::Container ^components;
#pragma region Windows Form Designer generated code
/// <summary>
/// Требуемый метод для поддержки конструктора — не изменяйте
/// содержимое этого метода с помощью редактора кода.
/// </summary>
void InitializeComponent(void)
{
this->start_btn = (gcnew System::Windows::Forms::Button());
this->label1 = (gcnew System::Windows::Forms::Label());
this->path_to_image = (gcnew System::Windows::Forms::TextBox());
this->path_to_txt = (gcnew System::Windows::Forms::TextBox());
this->label2 = (gcnew System::Windows::Forms::Label());
this->back_btn = (gcnew System::Windows::Forms::Button());
this->SuspendLayout();
//
// start_btn
//
this->start_btn->Location = System::Drawing::Point(17, 234);
this->start_btn->Name = L"start_btn";
this->start_btn->Size = System::Drawing::Size(154, 65);
this->start_btn->TabIndex = 0;
this->start_btn->Text = L"Выполнить";
this->start_btn->UseVisualStyleBackColor = true;
this->start_btn->Click += gcnew System::EventHandler(this, &enCoder::start_btn_Click);
//
// label1
//
this->label1->AutoSize = true;
this->label1->Location = System::Drawing::Point(30, 42);
this->label1->Name = L"label1";
this->label1->Size = System::Drawing::Size(505, 20);
this->label1->TabIndex = 1;
this->label1->Text = L"Укажите адрес изображения, в котором желаете спрятать текст\r\n";
//
// path_to_image
//
this->path_to_image->Location = System::Drawing::Point(17, 65);
this->path_to_image->Name = L"path_to_image";
this->path_to_image->Size = System::Drawing::Size(808, 26);
this->path_to_image->TabIndex = 2;
this->path_to_image->TextChanged += gcnew System::EventHandler(this, &enCoder::path_to_image_TextChanged);
//
// path_to_txt
//
this->path_to_txt->Location = System::Drawing::Point(17, 138);
this->path_to_txt->Name = L"path_to_txt";
this->path_to_txt->Size = System::Drawing::Size(808, 26);
this->path_to_txt->TabIndex = 3;
this->path_to_txt->TextChanged += gcnew System::EventHandler(this, &enCoder::path_to_txt_TextChanged);
//
// label2
//
this->label2->AutoSize = true;
this->label2->Location = System::Drawing::Point(30, 115);
this->label2->Name = L"label2";
this->label2->Size = System::Drawing::Size(489, 20);
this->label2->TabIndex = 4;
this->label2->Text = L"Укажите адрес текстового файла .txt, содержащего ваш текст";
//
// back_btn
//
this->back_btn->Location = System::Drawing::Point(657, 234);
this->back_btn->Name = L"back_btn";
this->back_btn->Size = System::Drawing::Size(163, 65);
this->back_btn->TabIndex = 5;
this->back_btn->Text = L"Назад";
this->back_btn->UseVisualStyleBackColor = true;
this->back_btn->Click += gcnew System::EventHandler(this, &enCoder::back_btn_Click);
//
// enCoder
//
this->AutoScaleDimensions = System::Drawing::SizeF(9, 20);
this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font;
this->ClientSize = System::Drawing::Size(1337, 895);
this->Controls->Add(this->back_btn);
this->Controls->Add(this->label2);
this->Controls->Add(this->path_to_txt);
this->Controls->Add(this->path_to_image);
this->Controls->Add(this->label1);
this->Controls->Add(this->start_btn);
this->Name = L"enCoder";
this->Text = L"Скрыть текст в картинке";
this->ResumeLayout(false);
this->PerformLayout();
}
#pragma endregion
private: System::Void path_to_txt_TextChanged (System::Object^ sender, System::EventArgs^ e) {
String^ pathToTxt = this->path_to_txt->Text;
}
private: System::Void path_to_image_TextChanged(System::Object^ sender, System::EventArgs^ e) {
String^ pathToImage = this->path_to_image->Text;
}
private: System::Void start_btn_Click (System::Object^ sender, System::EventArgs^ e);
private: System::Void back_btn_Click (System::Object^ sender, System::EventArgs^ e) {
this->Hide();
}
};
} |
|
0
|