Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

решения / blowfish

.cpp
Скачиваний:
4
Добавлен:
18.02.2023
Размер:
7.9 Кб
Скачать
//#include <iostream>
//#include <fstream>
//#include <sstream>
//#include <openssl/blowfish.h>
//
//#define BUFSIZE 1024
//
//using namespace std;
//
//void do_crypt(unsigned char* inbuf, unsigned char* outbuf, int len, unsigned char* key, int dir)
//{
//	int num = 0;
//	/* Ключ шифрования длиной 128 бит и вектор инициализации */
//	unsigned char iv[8];
//	BF_KEY bfkey;
//	/* Помещаем ключ в структуру bfkey */
//	BF_set_key(&bfkey, sizeof(key), key);
//	/* Шифруем блоки входного файла */
//	BF_cfb64_encrypt(inbuf, outbuf, BUFSIZE, &bfkey, iv, &num, dir);
//	// len - размер данных для шифрования
//	// bfkey - ключ
//	// iv - указатель на вектор инициализации
//	// num - сколько байт последнего 8-байтового блока мы используем
//	// dir - шифр/дешифр
//}
//
//int main()
//{
//	string filename = "";
//	char rawkey[16] = "";
//	int dir = BF_ENCRYPT;
//	setlocale(LC_ALL, "Russian");
//	cout << "Введите имя файла: ";
//	cin >> filename;
//	while (cin.fail())
//	{
//		cin.clear();
//		cin.ignore(numeric_limits<streamsize>::max(), '\n');
//		cout << "Некорректный ввод! Попробуйте снова: ";
//		cin >> filename;
//	}
//	cin.ignore(numeric_limits<streamsize>::max(), '\n');
//
//	cout << "Введите ключ: ";
//	cin.readsome(rawkey, sizeof(rawkey));
//	while (cin.fail())
//	{
//		cin.clear();
//		cin.ignore(numeric_limits<streamsize>::max(), '\n');
//		cout << "Некорректный ввод! Попробуйте снова: ";
//		cin.readsome(rawkey, sizeof(rawkey));
//	}
//	cin.ignore(numeric_limits<streamsize>::max(), '\n');
//	unsigned char* key = reinterpret_cast<unsigned char*> (rawkey);
//
//	cout << "Введите направление (1 - шифрование или 0 - расшифровывание): ";
//	cin >> dir;
//	while (cin.fail() || (dir != BF_ENCRYPT && dir != BF_DECRYPT))
//	{
//		cin.clear();
//		cin.ignore(numeric_limits<streamsize>::max(), '\n');
//		cout << "Некорректный ввод! Попробуйте снова: ";
//		cin >> dir;
//	}
//	cin.ignore(numeric_limits<streamsize>::max(), '\n');
//
//	ifstream fin(filename, ios::in);
//	if (!fin.is_open())
//	{
//		cout << "Произошла ошибка при открытии файла для чтения!" << endl;
//		return 0;
//	}
//	stringstream tmp;
//
//	while (fin.good())
//	{
//		char inbuf[BUFSIZE] = "";
//		unsigned char outbuf[BUFSIZE] = "";
//		if (dir == BF_ENCRYPT)
//		{ // шифрование
//			if (fin.get(inbuf, BUFSIZE))
//			{
//				unsigned char* converted_inbuf = reinterpret_cast<unsigned char*> (inbuf);
//				do_crypt(converted_inbuf, outbuf, BUFSIZE, &(*key), dir);
//				for (int i = 0; i < BUFSIZE; i++)
//					tmp << (int)outbuf[i] << " ";
//			}
//		}
//		else if (dir == BF_DECRYPT)
//		{
//			for (int i = 0; i < BUFSIZE; i++)
//			{
//				int ch = 0;
//				fin >> ch;
//				inbuf[i] = ch;
//			}
//			unsigned char* converted_inbuf = reinterpret_cast<unsigned char*> (inbuf);
//			do_crypt(converted_inbuf, outbuf, BUFSIZE, &(*key), dir);
//			char* converted_outbuf = reinterpret_cast<char*> (outbuf);
//			for (int i = 0; i < BUFSIZE - 1; i++)
//			{
//				if (converted_outbuf[i] == '\0')
//				{
//					dir = -1; // прерываем цикл
//					break;
//				}
//				tmp << converted_outbuf[i];
//			}
//		}
//		else break;
//	}
//	fin.close();
//	ofstream fout(filename, ios::out);
//	if (!fout.is_open())
//	{
//		cout << "Произошла ошибка при открытии файла для вывода!" << endl;
//		return 0;
//	}
//	while (!tmp.eof())
//	{
//		char buf[BUFSIZE] = "";
//		if (tmp.get(buf, BUFSIZE))
//			fout << buf;
//	}
//	cout << "Выполнено!" << endl;
//	return 0;
//}

// blowfish.cpp : Шифратор и дешифратор файлов симметричным алгоритмом Blowfish. 
// На вход программы передается входной файл, ключ, флаг шифрования/дешифрования, выходной файл.

//#include <iostream>
//#include <fstream>
//#include <sstream>
//#include <openssl/evp.h>
//#include <openssl/blowfish.h>
//
//#define BUFSIZE 1024
//
//using namespace std;
//
////int main(int argc, string argv[])
//int main()
//{
//	setlocale(LC_ALL, "Russian");
//	string argv[4] = { "-", "456.txt", "12345678", "0" };
//	for (int i = 1; i < 4; i++) cout << argv[i] << endl;
//
//	ifstream fin(argv[1], ios::in);
//	if (!fin.is_open())
//	{
//		cout << "Произошла ошибка при открытии файла для чтения!" << endl;
//		return 0;
//	}
//
//	fin.seekg(0, ios::end);
//	int fsize = (int)fin.tellg();
//	fin.seekg(0, ios::beg);
//
//	char* rawkey = new char[argv[2].length() + 1];
//	strcpy_s(rawkey, argv[2].length() + 1, argv[2].c_str());
//	unsigned char* key = reinterpret_cast<unsigned char*> (rawkey);
//	
//	int dir = (argv[3][0] == '1') ? BF_ENCRYPT : BF_DECRYPT;
//
//	unsigned char* inbuf = new unsigned char[fsize];
//	unsigned char* outbuf = new unsigned char[fsize];
//	int outlen = 0, outlenfinal = 0;
//	unsigned char iv[] = "dontusethisinput";
//	//Set up encryption
//	
//	for (int i = 0; i < fsize; i++)
//	{
//		char ch = 0;
//		ch = fin.get();
//		//if (ch == '\n') fsize--;
//		inbuf[i] = (unsigned char)ch;
//	}
//
//	EVP_CIPHER_CTX* ctx;
//	ctx = EVP_CIPHER_CTX_new();
//	EVP_CipherInit(ctx, EVP_bf_cfb(), key, iv, dir);
//	EVP_CipherUpdate(ctx, outbuf, &outlen, inbuf, fsize);
//	EVP_CipherFinal(ctx, outbuf + outlen, &outlenfinal);
//
//	fin.close();
//	delete[] rawkey;
//
//	ofstream fout("456.txt", ios::out);
//	if (!fout.is_open())
//	{
//		cout << "Произошла ошибка при открытии файла для вывода!" << endl;
//		return 0;
//	}
//	for (int i = 0; i < outlen; i++)
//	{
//		unsigned char ch = 0;
//		ch = outbuf[i];
//		fout.put((char)ch);
//	}
//	fout.close();
//	cout << "Выполнено!" << endl;
//	return 0;
//}

#define _CRT_SECURE_NO_WARNINGS

#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <openssl/evp.h>
#include <openssl/blowfish.h>

void crypt(FILE* ifp, FILE* ofp, unsigned char* key, int enc)
{
    //Get file size
    fseek(ifp, 0L, SEEK_END);
    int fsize = ftell(ifp);
    //set back to normal
    fseek(ifp, 0L, SEEK_SET);

    int outLen1 = 0; int outLen2 = 0;
    unsigned char* indata = new unsigned char[fsize];
    unsigned char* outdata = new unsigned char[fsize * 2];
    unsigned char ivec[] = "dontusethisinput";

    //Read File
    fread(indata, sizeof(char), fsize, ifp);//Read Entire File

    //Set up encryption
    EVP_CIPHER_CTX* ctx;
    ctx = EVP_CIPHER_CTX_new();
    EVP_CipherInit(ctx, EVP_bf_cfb(), key, ivec, enc);
    EVP_CipherUpdate(ctx, outdata, &outLen1, indata, fsize);
    EVP_CipherFinal(ctx, outdata + outLen1, &outLen2);
    fwrite(outdata, sizeof(char), outLen1 + outLen2, ofp);
}

int main(int argc, char* argv[])
{
    FILE* fIN, * fOUT;
    fIN = fopen(argv[1], "rb");//File to be encrypted; plain text
    printf("%s\n", argv[1]);
    printf("%s\n", argv[2]);
    printf("%s\n", argv[3]);
    printf("%s\n", argv[4]);
    fOUT = fopen(argv[4], "wb");//File to be written; cipher text

    unsigned char* key = new unsigned char[18];
    strncpy((char*)key, argv[2], 18);
    int enc = (argv[3][0] == 'd') ? 0 : 1;

    crypt(fIN, fOUT, key, enc);

    fclose(fIN);
    fclose(fOUT);
    return 0;
}


Соседние файлы в папке решения