我有一个加密和解密文件的代码,代码运行良好,但问题是当我尝试用不正确的密码解密文件而不是给出错误时,执行解密导致不同文件比原始文件。是否可以检查在解密中输入的密码是否与加密中使用的密码相同?
void AES::Encrypt(SymmetricKey key, InitializationVector iv, string inFilename, string outFilename)
{
ifstream in(inFilename.c_str(),std::ios::binary);
ofstream out(outFilename.c_str(),std::ios::binary);
QFile* file = new QFile(inFilename.c_str());
qint64 size = file->size();
qint64 i = 0;
percent = -1;
Pipe pipe(get_cipher("AES-256/CBC", key, iv,ENCRYPTION),new DataSink_Stream(out));
pipe.start_msg();
SecureBuffer<byte, 4096> buffer;
while(in.good())
{
in.read((char*)&buffer[0], buffer.size());
const size_t got_from_infile = in.gcount();
pipe.write(buffer, got_from_infile);
i += got_from_infile;
int p = ((i * 100) / size);
if (p != percent)
{
percent = p;
emit progress(percent);
}
if(in.eof()) pipe.end_msg();
while(pipe.remaining() > 0)
{
const size_t buffered = pipe.read(buffer, buffer.size());
out.write((const char*)&buffer[0], buffered);
}
}
out.flush();
out.close();
in.close();
qDebug() << "Encrypted!";
}
void AES::Decrypt(SymmetricKey key, InitializationVector iv, string inFilename, string outFilename)
{
ifstream in(inFilename.c_str(),std::ios::binary);
ofstream out(outFilename.c_str(),std::ios::binary);
QFile* file = new QFile(inFilename.c_str());
qint64 size = file->size();
qint64 i = 0;
percent = -1;
Pipe pipe(get_cipher("AES-256/CBC", key, iv,DECRYPTION),new DataSink_Stream(out));
pipe.start_msg();
SecureBuffer<byte, 4096> buffer;
while(in.good())
{
in.read((char*)&buffer[0], buffer.size());
const size_t got_from_infile = in.gcount();
pipe.write(buffer, got_from_infile);
i += got_from_infile;
int p = ((i * 100) / size);
if (p != percent)
{
percent = p;
emit progress(percent);
}
if(in.eof()) pipe.end_msg();
while(pipe.remaining() > 0)
{
const size_t buffered = pipe.read(buffer, buffer.size());
out.write((const char*)&buffer[0], buffered);
}
}
out.flush();
out.close();
in.close();
qDebug() << "Decrypted!";
}
答案 0 :(得分:0)
加密时,首先将未加密文件的全部内容的哈希附加到其末尾,然后加密新文件。因此,加密文件比未加密文件大几个字节。
解密后,首先检查末尾的散列是否有效,然后从文件中删除它以获取原始内容。