由于在 CBC
模式下使用 AES
方法加密字符串,我在 Qt 中使用了 Crypto++ 库并使用StringSource
和StringSink
来定义input
和output
字符串参数。
首先,我从文件中读取所有字节(“unicode”或“ASCII”编码),然后将其设置为StringSource
函数中的input
参数,然后设置参数为字符串(数据类型),用于输出(密文)。只是我想获取一个字符串并使用“aes-cbc”对其进行加密并显示输出。
此外,我知道 FileSource
和 FileSink
是两个函数(包含 input
和 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 字节)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/