我正在使用XTEA算法进行加密/解密程序。该加密器/解密功能正常工作,但是当我加密被一个文件,然后破译它,我得到一些额外的字符在文件的结尾:Ofstream将额外字符添加到我的输出中
--- Original file ---
QwertY
--- Encrypted file ---
»¦æŸ[email protected]±
--- Deciphered from encrypted ---
QwertY ß*tÞÇ
我不知道为什么“SS *tÞÇ”出现到底。 我会发布一些我的代码,但不是全部,因为它会太长。加密/解密功能需要64位数据和128位密钥,并将数据加密/解密为相同的块大小,这又是64位(similar functions here)。然后可以将其写入新文件。
long data[2]; // 64bits
ZeroMemory(data, sizeof(long)*2);
char password[16];
ZeroMemory(password, sizeof(char)*16);
long *key;
if(argc > 1)
{
string originalpath = argv[1];
string finalpath;
string eextension = "XTEA";
string extension = GetFileExtension(originalpath);
bool encipherfile = 1;
if(extension.compare(eextension) == 0) // If extensions are equal, dont encipher file
{
encipherfile = 0;
finalpath = originalpath;
finalpath.erase(finalpath.length()-5, finalpath.length());
}
ifstream in(originalpath, ios::binary);
ofstream out(finalpath, ios::binary);
cout << "Password:" << endl;
cin.get(password,sizeof(password));
key = reinterpret_cast<long *>(password);
while(!in.eof())
{
ZeroMemory(data, sizeof(long)*2);
in.read(reinterpret_cast<char*>(&data), sizeof(long)*2); // Read 64bits from file
if(encipherfile == 1)
{
encipher(data, key);
out.write(reinterpret_cast<char*>(&data), sizeof(data));
continue;
}
if(encipherfile == 0)
{
decipher(data, key);
out.write(reinterpret_cast<char*>(&data), sizeof(data));
}
}
[从文本文件读取直到EOF重复上一行]可能的重复(http://stackoverflow.com/questions/21647/reading-from-text-file-until-eof-repeats-last-line) – 2012-04-09 09:57:32
感谢您的链接,但我可以向你保证这不是重复的......你在你给我的链接中看到,他们一次只读1个字符。我一次读取一个64位块,即使块在EOF之前只接收1个字节,我仍然可以对它进行加密/解密,然后循环将不会再次运行。 – Janman 2012-04-09 11:35:18
该块实际上在EOF之前接收到零个字节。你仍然破译并再写一次。关键是'in.eof()'告诉我们上一次读取是否失败,而不是下一次读取是否成功。 – 2012-04-09 12:36:01