2

我在Qt中使用了Crypto++库,因为使用模式中的方法加密字符串并使用 of和定义字符串参数。AESCBCStringSourceStringSinkinputoutput

首先,我从文件中读取所有字节(“unicode”或“ASCII”编码),然后将其设置为函数中的input参数StringSource,然后将参数设置为string(数据类型)用于输出(密文)。只是我想得到一个字符串并用“aes-cbc”加密它并显示输出。

另外,我知道FileSource并且是用于将数据写入文件FileSink的两个函数(consistinput和流参数)!output但我想将文件内容作为输入字符串读取。

我的代码:

void Widget::onEncryptButton()
{
    QByteArray key = "qwertyuiopasdfgh";
    QByteArray iv = "wertyuiopasdfghj"
    QByteArray plain;
    string cipher;

    QFile fi("/home/msi/Desktop/input.txt");
    QFile fo("/home/msi/Desktop/output.enc");

    fi.open(QFile::ReadOnly);
    fo.open(QFile::WriteOnly);
    plain = fi.readAll();

    AESEncryption aese((byte*)key.constData(), AES::DEFAULT_KEYLENGTH);    // default is 16
    CBC_Mode_ExternalCipher::Encryption encryptor(aese, (byte*)iv.constData());
    StringSource(plain, true, new StreamTransformationFilter(encryptor, new StringSink(cipher)));

    QMessageBox::information(this, "", QString("%1, %2").arg(strlen(cipher.c_str())).arg(cipher.size()));    // just for viewing cipher length

    fo.write(cipher.c_str());
    fi.close();
    fo.close();
}

现在我有以下问题:

  • 当我读取压缩文件内容(例如 900 字节)并将其设置为输入时StringSource,生成的密码将不完整(例如 320 字节)

  • “QMessageBox”中的输出strlen(cipher.c_str())不同cipher.size()

  • 我的代码真正工作当我阅读一些文件(“unicode”或“ASCII”,“大”或“小”大小)并且有时工作不正确时。我不明白是哪个原因导致了这个问题?

  • 甚至,我直接设置了一些输入字符串(不是从文件中读取)并再次失败!

问候!

4

3 回答 3

1

我会考虑重新设计该功能:

// Improve this in real life
QByteArray key = "qwertyuiopasdfgh";
QByteArray iv = "wertyuiopasdfghj"

std::string infile("/home/msi/Desktop/input.txt");
std::string outfile("/home/msi/Desktop/output.enc");

CBC_Mode<AES>::Encryption encryptor(key.constData(), key.size(), iv.constData());
FileSource fs(infile.c_str(), true, new StreamTransformationFilter(encryptor, new FileSink(outfile.c_str())));

使用FileSourceandFileSink避免了试图在字符集下解释数据的问题。它还节省了额外的副本,并且对没有大量 RAM 的移动设备和物联网小工具更友好。

您还可以考虑使用Authenticated Encryption 模式来确保机密性和真实性。

于 2016-07-18T22:10:57.243 回答
1

我可以是你的plain,如果它包含'\0'。尝试同时传递数据和长度:

StringSource((byte*)plain.constData(), plain.size(), true, new StreamTransformationFilter(encryptor, new StringSink(cipher)));
于 2016-07-18T08:47:42.763 回答
0

我替换下面的声明:

StringSource((byte*)plain.constData(), plain.size(), true, new StreamTransformationFilter(encryptor, new StringSink(cipher)));

随着波纹管:

StringSource(plain, true, new StreamTransformationFilter(encryptor, new StringSink(cipher)));

然后,我再次重建程序,但问题仍然存在!

暂时从明文中删除所有'\'字符并再次编译,之后,输出密码在“QMessageBox”中真正显示了cipher.size()语句。

然后替换

fo.write(cipher.c_str(), cipher.size());

和 :

fo.write(cipher.c_str());

我对加密和解密部分执行这些说明。

于 2016-07-18T11:15:57.197 回答