-2

我正在使用 Crypto++ 加密和解密文件。在加密中,key 随机IV生成和hexencoded文件中的文本在哪里被加密。IV和text都cipher写入同一个文件。

在解密中,key使用与加密相同的标准生成,随机IV从文件中提取,hexdecoded. iv长度后的文本存储在字符串中并解密。

发生的情况是我可以看到原始文件,所以我知道它正在工作,但它还cipher在原始文件文本之后显示文本。有没有人如何解决它?

 //some code to declare variables, read from file and so on 

  unsigned char * inputContent = (unsigned char *) malloc(fileSize * sizeof(char));     //create char array of same size as file content 

 //inputContent is for storing file data    

  string rawString(reinterpret_cast<char*>(inputContent), fileSize);        //convert char array to string

  //extract iv, key and cipher from rawString
  string rawIV;
  rawIV = rawString.substr(0, 32);

  //code to hexdecode iv

  string cipher;
  cipher = rawString.substr(32, fileSize - 32);

  string recovered;

  CBC_Mode< AES >::Decryption d;
  d.SetKeyWithIV(key, sizeof(key), iv);

  StringSource s_recover(cipher, true, 
      new StreamTransformationFilter(d,
                new StringSink(recovered)
            )
        );  

  const char * writeContent = recovered.c_str();

  if(pwrite(fd, writeContent, recovered.length(), 0) <= 0)
  {
      return -1;    //error
  }

提前致谢。☺</p>

4

1 回答 1

0

你可能会尝试这样的事情。但很难说它是否真的有效,因为它不清楚你实际上在做什么或问题出在哪里。

FileSource fs("<filename>", false /*pumpAll*/);    
SecByteBlock key(AES::DEFAULT_KEYLENGTH), iv(AES::BLOCKSIZE);

// Fetch key from somewhere
key = ...;

// Fetch IV from file
fs.Detach(new HexDecoder(new ArraySink(iv, iv.size()));
fs.Pump(32);

CBC_Mode< AES >::Decryption dec;
dec.SetKeyWithIV(key, key.size(), iv, iv.size());

string recovered;
fs.Detach(new HexDecoder(new StreamTransformationFilter(dec, new StringSink(recovered))));
fs.PumpAll();

如果您获得SecByteBlockSink补丁,您还可以使用以下内容:

SecByteBlock recovered;
fs.Detach(new HexDecoder(new StreamTransformationFilter(dec, new SecByteBlockSink(recovered))));
fs.PumpAll();

rawString下面不需要:

//create char array of same size as file content 
unsigned char * inputContent = (unsigned char *) malloc(fileSize * sizeof(char));     

//inputContent is for storing file data    

//convert char array to string
string rawString(reinterpret_cast<char*>(inputContent), fileSize);

也许你应该尝试:

ArraySource as(inputContent, fileSize, false /*pumpAll*/);

使用这种ArraySource方法您不会复制数据(string复制数据),并且可以使用 Crypto++。

此外,由于您已经熟悉 C++ 代码,请使用unique_ptrandnew而不是malloc. unique_ptr将为您处理清理工作。(或者,使用 a std::vector)。

unique_ptr<byte[]> buffer(new byte[fileSize]);

我不知道您将如何使文件描述符在宏伟的计划中工作。Crypto++ 是一个 C++ 库,而 C++ 使用 I/O 流。也许这会有所帮助:如何从 POSIX 文件描述符构造 c++ fstream?

另请参阅从 std::fstream 检索文件描述符和从 std::fstream获取FILE*

于 2015-04-21T21:48:07.527 回答