Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Gibridnoe_shifrovanie.docx
Скачиваний:
0
Добавлен:
01.04.2025
Размер:
32.64 Кб
Скачать

Расшифрование

// Shifr.cpp: определяет точку входа для консольного приложения.

//

#include "stdafx.h"

#include <iostream>

#include <conio.h>

#include <WinCrypt.h>

#pragma comment (lib,"advapi32.lib")

using namespace std;

int main()

{

setlocale(0,"RUS");

HCRYPTPROV hProv = NULL;

HCRYPTHASH hHash=NULL;

LPCSTR UserName = "SSContainer";

HCRYPTKEY hKey, hPublicKey, hNewKey;

DWORD BS=0;

BYTE pbBuffer[4096];

int i=0;

////////Извлекаем текст

printf("\nText: ");

FILE *pf;

char ch;

if((pf=fopen("text.txt","r"))!=NULL)

{

do

{

ch=getc(pf);

if(!feof(pf))

{

pbBuffer[i]=(BYTE)ch;

printf("%c",pbBuffer[i]);

i++;

BS=i;

}

}

while(!feof(pf));

fclose(pf);

}

// Инициализация контекста криптопровайдера (с указанием имени

// контейнера ключей)

if (!CryptAcquireContext(&hProv,(LPCTSTR)UserName,NULL,PROV_RSA_FULL,0)) return 0;

std::cout << "\nCryptographic provider initialized" << std::endl;

////////

// Генерация ключа

if(!CryptCreateHash(hProv, CALG_MD5, 0, 0, &hHash))

{

printf("Error during CryptCreateHash!\n");

return 0;

}

else printf("\nСоздание хеш-объекта завершено...\n");

/////

if (!CryptDeriveKey(hProv,CALG_RC4,hHash,CRYPT_EXPORTABLE,&hKey)) return 0;

std::cout << "Session key generated\n" << std::endl;

// Получение ключа для экспорта ключа шифрования

if (!CryptGetUserKey(hProv, AT_KEYEXCHANGE, &hPublicKey)) return 0;

std::cout << "Public key is received" << std::endl;

DWORD pbwDataLen=0;

LPBYTE pbData=NULL;

if (!CryptExportKey(hKey, hPublicKey,SIMPLEBLOB,0,0,&pbwDataLen))

return 0;

std::cout << "\nSize blob determined" << std::endl;

if(pbData = (LPBYTE)malloc(pbwDataLen))

{

printf("\nMemory has been allocated for the BLOB. ");

}

else

{

printf("\nOut of memory. ");

return 0;

}

if (!CryptExportKey(hKey, hPublicKey,SIMPLEBLOB,0,pbData,&pbwDataLen))

return 0;

std::cout << "\nBLOB is completed" << std::endl;

if(!CryptEncrypt(hKey,0,true,0,pbBuffer,&BS,BS))

{

printf("\nError during CryptDeriveKey!");

return 0;

}

else printf("\nТекст зашифрован...");

////////Сохраняем в файле

FILE *pfo;

if((pfo=fopen("shifr.txt","w"))!=NULL)

{

for(i=0;i<BS;i++)

{

fprintf(pfo,"%c",pbBuffer[i]);

}

fclose(pfo);

printf("\nТекст сохранен в файле \"shifr.txt\"...");

}

CryptDestroyKey(hKey);

CryptDestroyKey(hPublicKey);

CryptDestroyHash(hHash);

CryptReleaseContext(hProv,0);

If (!CryptAcquireContext(&hProv,(lpctstr)UserName,null,prov_rsa_full,0)) return 0;

std::cout << "\nCryptographic provider initialized" << std::endl;

// Получение ключа для экспорта ключа шифрования

If (!CryptGetUserKey(hProv, at_keyexchange, &hPublicKey)) return 0;

std::cout << "\nPublic key is received" << std::endl;

DWORD dwErr=NULL;

// Импорт ключа шифрования из полученного массива данных

if(!CryptImportKey(hProv,pbData,pbwDataLen,hPublicKey,SIMPLEBLOB,&hNewKey))if (ERROR_NO_MORE_ITEMS != (dwErr = GetLastError()))

{printf("ERROR - CryptEnumProviders : %X\n", dwErr); return 0;

}

std::cout << "Key's import completed" << std::endl;

printf("BLOB: \n");

for(i=0;i<pbwDataLen;i++)

{

printf("%c",pbData[i]);

}

printf("\n----------------------------------------------------------- \n");

// Расшифрование данных

DWORD j=0;

if(!CryptDecrypt(hNewKey,0,true,0,pbBuffer,&BS))

{

printf("Error during CryptDecrypt!\n");

return 0;

}

else printf("Текст расшифрован...\n");

printf("(%d)Текст: \n",BS);

for(j=0;j<BS;j++)

{

printf("%c",pbBuffer[j]);

}

////////Сохраняем в файле

if((pfo=fopen("text1.txt","w"))!=NULL)

{

for(i=0;i<BS;i++)

{

fprintf(pfo,"%c",pbBuffer[i]);

}

fclose(pfo);

printf("\nТекст сохранен в файле \"text1.txt\"...\n");

}

CryptDestroyKey(hPublicKey);

CryptDestroyKey(hNewKey);

CryptReleaseContext(hProv,0);

return 0;

}

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]