-2

Crypto++ を使用してファイルの暗号化と復号化に取り組んでいます。暗号化ではkey 、ランダムIVが生成さhexencodedれ、ファイルからのテキストが暗号化されます。IVcipherテキストの両方が同じファイルに書き込まれます。

復号化で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_ptrandを使用してください。がクリーンアップを処理します。(または、を使用します)。newmallocunique_ptrstd::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 に答える