我正在使用XTEA算法进行加密/解密程序。加密/解密函数工作正常,但是当我加密文件然后解密它时,我在文件的末尾会得到一些额外的字符:
--- Original file ---
QwertY
--- Encrypted file ---
»¦æŸS@±
--- Deciphered from encrypted ---
QwertY ß*tÞÇ
我不知道为什么最后会出现“ß*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));
}
}
答案 0 :(得分:0)
在您阅读后立即检查eof
,以及eof
是否已退出循环。
如果您可能有部分读取(即可以读取少于所有请求的字节),那么您还需要调用gcount
来查找实际读取的字节数,因此:
cin.read( ... )
if( cin.eof() )
{
streamsize bytesRead = cin.gcount();
if( bytesRead > 0 )
// process those bytes
break;
}