2

我有一个加密和解密文件的代码,该代码运行良好,但问题是当我尝试使用不正确的密码解密文件时,而不是给出错误,执行解密导致文件与原始文件。是否可以检查在解密中输入的密码是否与加密中使用的密码相同?

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!";
}
4

1 回答 1

1

加密时,首先将未加密文件的全部内容的哈希附加到其末尾,然后对新文件进行加密。因此,加密文件将比未加密文件大几个字节。

解密后,首先检查最后的hash是否有效,然后从文件中剥离得到原始内容。

于 2012-12-10T05:08:38.300 回答