This line might be the source:
fileStreamIn.read(&buffer.front(), buffer_size);
The content of a
std::string
should not be modified directly. You are using
front()
here which allows the modification of the referenced character. But you are using it to modifiy the string content. Because
ifstream::read()
does not append a NULL character, this might work with the first call (when the string is still filled with NULL chars) but results in remaining characters when less has been read in which probably occurs with the last reading.
[EDIT]
Additionally the string is re-used later by assigning the encoded string and then set to an empty string (which effectively places a NULL character in front). As a result there are random characters at the end of the string when the next reading from file did not not use the full length.
[/EDIT]
I would not use
std::string
as buffer type here but just a
char
array and append a NULL byte after reading. If you don't want to rewrite your
decode
function to use a
char*
, just pass a temporary string (std::string(buffer)).
[EDIT]
When using a
char
array, the size must be one more than the max. number of chars read in from file to store the terminating NULL character.
[EDIT]
[EDIT 2]
A possible solution reading the whole file into a string and decoding it afterwards (untested):
void decodeFile(string inputFileName,string outputFileName,string keyFileName)
{
string fileBuffer;
ifstream fileStreamIn(inputFileName,ios::binary);
ofstream fileStreamOut(outputFileName,ios::binary);
while(fileStreamIn)
{
char readBuffer[385];
fileStreamIn.read(readBuffer, sizeof(read_buffer) - 1);
size_t count = fileStreamIn.gcount();
readBuffer[count] = '\0';
fileBuffer += readBuffer;
}
std::string decoded;
decode(fileBuffer, decoded, keyFileName);
fileStreamOut.write(decoded.c_str(), decoded.length());
fileStreamIn.close();
fileStreamOut.close();
}
};
And another tip:
When passing strings you should pass them by reference. Actually you will always create a copy of the string. Additionally, strings that are not modified should be const. The resulting function definitions are then:
void decodeFile(const string& inputFileName, const string& outputFileName, const string& keyFileName);
void decode(const string& in, string &out, const string& keyFileName);
Similar for the other functions. But note that the
const
modifier can not be used when calling another function that expects a non-const parameter (this might be so for
LoadPrivateKey()
and
ss2()
).