我目前正在尝试制作一个加密二进制文件(.zip)的简单程序,将其保存为另一种格式(.cry),然后将 .cry 文件解密回其原始状态。
我没有收到任何错误,但是当我尝试打开解密的 .zip 文件时,存档程序出现错误。
注意:原始 .zip 文件仅包含一个小 .txt 文件,其中写有 3 个单词。
#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>
#include <openssl/evp.h>
#include <openssl/rand.h>
int main(){
const EVP_CIPHER* pCipher = EVP_aes_128_ecb();
EVP_CIPHER_CTX* pCtx = new EVP_CIPHER_CTX;
//int nBl = EVP_CIPHER_CTX_block_size( pCtx );
FILE *fin;
FILE *fout;
FILE *fdecr;
long fin_size,fout_size,fdecr_size;
unsigned char *fin_buf;
unsigned char *fout_buf;
unsigned char *fdecr_buf;
size_t rezultat;
fin = fopen("arhiva.zip", "rb");
fout = fopen("arhiva.zip.cry","wb");
fdecr= fopen("decript.zip","wb");
if (fin==NULL)
{fputs ("File error",stderr); exit (1);}
if (fout==NULL)
{fputs ("File error",stderr); exit (1);}
if (fdecr==NULL)
{fputs ("File error",stderr); exit (1);}
fseek (fin , 0 , SEEK_END);
fin_size = ftell (fin);
fout_size=fin_size;
fdecr_size=fin_size;
rewind (fin);
fin_buf = (unsigned char*) malloc (sizeof(unsigned char)*fin_size);
fdecr_buf= (unsigned char*) malloc (sizeof(unsigned char)*fin_size);
if (fin_buf == NULL) {fputs ("Memory error",stderr); exit (2);}
//if (fout_buf == NULL) {fputs ("Memory error",stderr); exit (2);}
if (fdecr_buf == NULL) {fputs ("Memory error",stderr); exit (2);}
//copiere fisier in buffer
rezultat = fread (fin_buf,1,fin_size,fin);
if (rezultat != fin_size) {fputs ("Reading error",stderr); exit (3);}
//pregatire criptare
OpenSSL_add_all_ciphers();
EVP_CIPHER_CTX_init( pCtx );
unsigned char pKey[192];
unsigned char pIV[192];
RAND_bytes(pKey,24);
RAND_bytes(pIV,24);
EVP_EncryptInit_ex( pCtx, pCipher, NULL, pKey, pIV);
EVP_DecryptInit_ex( pCtx, pCipher, NULL, pKey, pIV);
//cript
int nOutLen = 0;
int nTmpOutLen = 0;
fout_buf = (unsigned char*) malloc (sizeof(unsigned char)*fout_size);
memset( fout_buf, 0, fout_size);
EVP_EncryptUpdate( pCtx,fout_buf,&nTmpOutLen,fin_buf,fin_size );
nOutLen += nTmpOutLen;
EVP_EncryptFinal( pCtx,fout_buf + nTmpOutLen,&nTmpOutLen );
fwrite(fout_buf, 1, fout_size, fout);
//decript
nOutLen = 0;
nTmpOutLen = 0;
memset( fdecr_buf, 0, fdecr_size);
EVP_DecryptUpdate(pCtx,fdecr_buf,&nTmpOutLen,fout_buf,fout_size );
nOutLen += nTmpOutLen;
EVP_DecryptFinal( pCtx,fdecr_buf + nTmpOutLen,&nTmpOutLen );
fwrite(fdecr_buf, 1, fdecr_size, fdecr);
fclose(fin);
fclose(fout);
fclose(fdecr);
EVP_CIPHER_CTX_cleanup(pCtx);
return 0;
}