【发布时间】:2012-12-09 22:52:44
【问题描述】:
我有一个加密和解密文件的代码,该代码运行良好,但问题是当我尝试使用错误密码解密文件时,不是给出错误,而是执行解密导致不同文件比原始文件。是否可以检查解密时输入的密码是否与加密时相同?
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!";
}
【问题讨论】:
-
加密前加一个hash,解密后检查。
-
密码哈希还是文件哈希?
-
文件的哈希值会更好。
标签: c++ qt encryption aes botan