c++ - AES 在 Qt 的 StringSource 和 StringSink 函数中无法正常工作

标签 c++ qt aes crypto++ cbc-mode

由于在 CBC 模式下使用 AES 方法加密字符串,我在 Qt 中使用了 Crypto++ 库并使用StringSourceStringSink来定义inputoutput字符串参数。

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

此外,我知道 FileSourceFileSink 是两个函数(包含 inputoutput 流参数)将数据写入文件!但我想读取文件内容作为输入字符串。

我的代码:

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 字节)

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

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

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

问候!

最佳答案

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

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

关于c++ - AES 在 Qt 的 StringSource 和 StringSink 函数中无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38431256/

相关文章:

python - 如何在 tkinter 中返回光标下的单词?

c++ - 将 find 与 QAssociativeIterable 或 QSequentialIterable 一起使用,同时避免在 Qt5 中进行复制

c++ - 数百个空闲线程的影响

c++ - Qt - 读取包含多个空字符的文件

c++ - 将表传递给 c/c++ 的简单 lua 示例

C++ AES如何逐 block 加密数据

java - 附加到 CipherOutputStream - AES/CTR/NoPadding (Java)

在 C 中使用 AES-256 和 openssl 计算 CBC-MAC

c++ - 是否可以模拟模板<auto X>?

c++ - 如何将类的方法传递给 C++ 中的另一个函数?