I have using of Crypto++ library in Qt due to encrypt a string with AES
method in CBC
mode and using of StringSource
and StringSink
to define input
and output
string parameters.
First, i read all bytes from a file ("unicode" or "ASCII" encoding), then set it as the input
parameter in StringSource
function, then set a parameter as string
(data-type) for output (cipher-text). just i want to get a string and encrypt it with "aes-cbc" and showing output.
Also, i know FileSource
and FileSink
are two functions(consist input
and output
stream parameters) for writing data to files! but i want to read file content as input-string.
My Code :
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();
}
Now i have bellow problems :
When i read a compact file content(e.g. 900 byte) and set it as input in StringSource
, generated cipher will be incomplete (e.g. 320 byte)
Output of strlen(cipher.c_str())
is different by cipher.size()
in "QMessageBox"
My code working truly When i read some files("unicode" or "ASCII", "larg" or "little" size) and sometimes working incorrectly. i dont understand which of the reason caused this problem?
Regards!
I could be your plain
, if it contains '\0'. Try to pass both, the data and the length:
StringSource((byte*)plain.constData(), plain.size(), true, new StreamTransformationFilter(encryptor, new StringSink(cipher)));