以下是代码:
#include <QCoreApplication>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <openssl/evp.h>
#include <openssl/aes.h>
#include <iostream>
void en_de_crypt(int should_encrypt, FILE *ifp, FILE *ofp, unsigned char *ckey, unsigned char *ivec) {
const unsigned BUFSIZE=4096;
unsigned char *read_buf = (unsigned char*)malloc(BUFSIZE);
unsigned char *cipher_buf;
unsigned blocksize;
int out_len;
EVP_CIPHER_CTX ctx;
for(int i=0; i<8;i++)
{
printf("%c\n",ckey[i]);
}
printf("\n\n");
for(int i=0; i<8;i++)
{
printf("%c\n",ivec[i]);
}
EVP_CipherInit(&ctx, EVP_aes_256_cbc(), ckey, ivec, should_encrypt);
blocksize = EVP_CIPHER_CTX_block_size(&ctx);
cipher_buf = (unsigned char *)malloc(BUFSIZE + blocksize);
while (1) {
// Read in data in blocks until EOF. Update the ciphering with each read.
int numRead = fread(read_buf, sizeof(unsigned char), BUFSIZE, ifp);
EVP_CipherUpdate(&ctx, cipher_buf, &out_len, read_buf, numRead);
fwrite(cipher_buf, sizeof(unsigned char), out_len, ofp);
if (numRead < BUFSIZE) { // EOF
break;
}
}
// Now cipher the final block and write it out.
EVP_CipherFinal(&ctx, cipher_buf, &out_len);
fwrite(cipher_buf, sizeof(unsigned char), out_len, ofp);
// Free memory
free(cipher_buf);
free(read_buf);
}
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
std::string pathToFiles = "C:/Temp/testEnc/dqdokoleda.7z";
unsigned char ckey[8];
unsigned char ivec[8];
ckey[0] = 'p';
ckey[1] = 'a';
ckey[2] = 's';
ckey[3] = 's';
ckey[4] = 'w';
ckey[5] = 'o';
ckey[6] = 'r';
ckey[7] = 'd';
ivec[0] = 'a';
ivec[1] = 'c';
ivec[2] = 'g';
ivec[3] = 't';
ivec[4] = 'i';
ivec[5] = 'j';
ivec[6] = 'o';
ivec[7] = 'r';
FILE *fIN, *fOUT;
// First encrypt the file
fIN = fopen((pathToFiles).c_str(), "rb"); //File to be encrypted; plain text
fOUT = fopen((pathToFiles+".enc").c_str(), "wb"); //File to be written; cipher text
en_de_crypt(1, fIN, fOUT, ckey, ivec);
fclose(fIN);
fclose(fOUT);
//Decrypt file now
fIN = fopen((pathToFiles+".enc").c_str(), "rb"); //File to be read; cipher text
fOUT = fopen((pathToFiles+".decrypted").c_str(), "wb"); //File to be written; cipher text
en_de_crypt(0, fIN, fOUT, ckey, ivec);
fclose(fIN);
fclose(fOUT);
std::cout << "END" << std::endl;
return a.exec();
}
问题在于当我注释解密部分时,每次.enc文件的内容都不同。然后,如果我尝试分别解密并注释加密代码的部分,文件将无法正确解密(7zip说它无法打开它)。如果我不注释任何代码部分,则加密和解密将成功完成。
我正在使用QT5.5.1,在文件加密和解密之间,我会进行清理、运行qmake、重新构建,并使用MSVC 12.0编译器以调试模式运行(这并不重要,但如果程序对您有效,请尝试在一个文件的加密和解密之间进行清理和构建,以查看它是否像应该那样工作)。