I'm trying to use QCA to encrypt/decrypt files.
When i use this code to encrypt, everything works fine (or seems to, at least).
But when i try to decrypt, the process() method returns an empty SecureArray.
Does anyone have an idea why and/or how to fix it?
void FileCrypto::crypt(QByteArray key, bool crypt){
QCA::Initializer init;
open();
Cipher cipher = initializeCipher(key, crypt);
QTextStream in(source); //lecture ligne par ligne
while (!in.atEnd()) {
QString line = in.readLine();
SecureArray secureData = line.toAscii().data(); //securise les donnees
if(!crypt)
QString temp = QString::fromAscii(secureData.toByteArray().toHex());
qDebug() << "Données lues : " << secureData.data();
SecureArray cryptedData = cipher.process(secureData); //(de)crypte les donnees
qDebug() << "Données cryptées :" << cryptedData.data();
destination->write(cryptedData.data()); //ecris dans le nouveau fichier
}
close();
}
void FileCrypto::open() throw (QString){
if(!source->open(QIODevice::ReadOnly | QIODevice::Text)
|| !destination->open(QIODevice::WriteOnly | QIODevice::Text)){
throw QString("Impossible d'ouvrir les fichiers cibles.");
}
}
void FileCrypto::close(){
source->close();
destination->close();
}
Cipher FileCrypto::initializeCipher(QByteArray akey, bool crypt){
QCA::InitializationVector iv;
Direction direction;
SymmetricKey key = SymmetricKey(akey);
iv = InitializationVector(akey);
if(crypt){
direction = Encode;
}else{
direction = Decode;
}
return Cipher(QString("blowfish"),Cipher::CBC,
Cipher::DefaultPadding, direction, key, iv);
}
Related
We are trying to use openSSL to encrypt a string with a public key, and then decrypt it with the private key.
Curiously, the workflow sometimes works, and sometimes it does not work (for the same keys and texts) and throws an error.
First, the private and public key are generated by:
openssl req -newkey rsa:2048 -new -nodes -x509 -days 3650 -keyout key.pem -out cert.pem
openssl rsa -in key.pem -outform PEM -pubout -out public.pem
After that, the code below is executed.
#include <iostream>
using namespace std;
#include <cstring>
#include <openssl/bio.h>
#include <openssl/err.h>
#include <openssl/ssl.h>
const int PADDING = RSA_PKCS1_OAEP_PADDING;
RSA *createRSAWithFilename(const char *filename, int pub)
{
FILE *fp = fopen(filename, "rb");
if (fp == NULL)
{
printf("Unable to open file %s \n", filename);
return NULL;
}
RSA *rsa = RSA_new();
if (pub)
{
rsa = PEM_read_RSA_PUBKEY(fp, &rsa, NULL, NULL);
}
else
{
rsa = PEM_read_RSAPrivateKey(fp, &rsa, NULL, NULL);
}
return rsa;
}
int public_encrypt(unsigned char *data, int data_len, RSA *rsa, unsigned char *encrypted)
{
int result = RSA_public_encrypt(data_len, data, encrypted, rsa, PADDING);
return result;
}
int private_decrypt(unsigned char *enc_data, int data_len, RSA *rsa, unsigned char *decrypted)
{
int result = RSA_private_decrypt(data_len, enc_data, decrypted, rsa, PADDING);
return result;
}
int main()
{
std::string textToBeEncoded="hi";
unsigned char plaintext[1024] = {0};
unsigned char encrypted[4098]= {0};
unsigned char decrypted[4098]={0};
strcpy((char *)plaintext,textToBeEncoded.c_str());
RSA *rsaPublic=createRSAWithFilename("public.pem", 1);
memset(encrypted,0,4098);
int en_result=public_encrypt(plaintext, strlen((char *)plaintext), rsaPublic, encrypted);
//fprintf(stderr, "Error: %s\n", ERR_error_string(ERR_get_error(), NULL));
RSA *rsaPrivate=createRSAWithFilename("key.pem", 0);
memset(decrypted,0,4098);
int de_result=private_decrypt(encrypted, strlen((char *)encrypted), rsaPrivate, decrypted);
//fprintf(stderr, "Error: %s\n", ERR_error_string(ERR_get_error(), NULL));
std::cout << "Result EN: " + std::to_string(en_result) << std::endl;
std::cout << "Result DE: " + std::to_string(de_result) << std::endl;
std::string decryptedString = std::string((const char *)decrypted);
std::cout << "DECRYPTED: " + decryptedString << " END."<< std::endl;
return 0;
}
Output:
At one time, the output looks okay and 0 (No error) is the only error code:
Error: error:00000000:lib(0)::reason(0) // error code=0 after encryption
Error: error:00000000:lib(0)::reason(0) // error code=0 after decryption
Result EN: 256
Result DE: 2
DECRYPTED: hi END.
At another time, the output is this:
Error: error:00000000:lib(0)::reason(0) // error code=0 after encryption
Error: error:02000079:rsa routines::oaep decoding error // ERROR after decryption
Result EN: 256
Result DE: -1
DECRYPTED: END.
Can someone help?
Best regards!
I want to write a file.
At first I have to encrypt the string "Banking;k1OI<]uH|V&r" using SimpleCrypt.
SimpleCrypt's code:
QString SimpleCrypt::encryptToString(const QString& plaintext)
{
QByteArray plaintextArray = plaintext.toUtf8();
QByteArray cypher = encryptToByteArray(plaintextArray);
QString cypherString = QString::fromLatin1(cypher.toBase64());
return cypherString;
}
The crash happens at m_keyParts.isEmpty() with an access violation
QByteArray SimpleCrypt::encryptToByteArray(QByteArray plaintext)
{
if (m_keyParts.isEmpty()) {
qWarning() << "No key set.";
m_lastError = ErrorNoKeySet;
return QByteArray();
}
// [...]
// Rest of the code
}
Does somebody know what to do?
Thanks in advance
Edit
Stacktrace:
Accessibles.exe!QVector::isEmpty() Zeile 91 C++
Accessibles.exe!SimpleCrypt::encryptToByteArray(QByteArray plaintext)
Zeile 55 C++ Accessibles.exe!SimpleCrypt::encryptToString(const
QString & plaintext) Zeile 118 C++ Accessibles.exe!DataStream::save()
Zeile 40 C++
Calling code:
textStream << p_simpleCrypt->encryptToString(QString("%1;%2\n").arg(bundle->category).arg(bundle->categoryId));
Is there a way to turn of log messages when calling QGLShaderProgram::link()?
http://qt-project.org/doc/qt-4.8/qglshaderprogram.html#link
Messages look like:
QGLShader::link: "Vertex shader(s) linked, fragment shader(s) linked.
"
Qt code looks like this:
src/opengl/qglshaderprogram.cpp:893
glLinkProgram(program);
value = 0;
glGetProgramiv(program, GL_LINK_STATUS, &value);
d->linked = (value != 0);
value = 0;
glGetProgramiv(program, GL_INFO_LOG_LENGTH, &value);
d->log = QString();
if (value > 1) {
char *logbuf = new char [value];
GLint len;
glGetProgramInfoLog(program, value, &len, logbuf);
d->log = QString::fromLatin1(logbuf);
QString name = objectName();
if (name.isEmpty())
qWarning() << "QGLShader::link:" << d->log;
else
qWarning() << "QGLShader::link[" << name << "]:" << d->log;
delete [] logbuf;
}
return d->linked;
}
So it seems the only possible solution is to redirect qWarning() as done in: How to redirect qDebug, qWarning, qCritical etc output?
qInstallMsgHandler([](QtMsgType , const char* ) { }); // empty message handler
bool result = program.link();
qInstallMsgHandler(0); // restore default message handling
I am writing a class to parse Itunes Libray File using QXmlQuery and QT-XSLT.
Here's my sample code:
ItunesLibParser::ItunesLibParser()
{
pathToLib = QString("/Users/rakesh/temp/itunes_xslt/itunes_music_library.xml");
}
void ItunesLibParser::createXSLFile(QFile &inFile)
{
if (inFile.exists()) {
inFile.remove();
}
inFile.open(QIODevice::WriteOnly);
QTextStream out(&inFile);
out << QString("<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>");
out << QString("<xsl:stylesheet version=\"2.0\" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\">");
out << QString("<xsl:output method=\"text\" />");
out << QString("<xsl:template name=\"playlistNames\">");
out << QString("<xsl:value-of select=\"child::integer[preceding-sibling::key[1]='Playlist ID']\"/>");
out << QString("<xsl:text>
</xsl:text>");
out << QString("<xsl:value-of select=\"child::string[preceding-sibling::key[1]='Name']\"/>");
out << QString("<xsl:text>
</xsl:text>");
out << QString("</xsl:template>");
out << QString("<xsl:template match=\"/\">");
out << QString("<xsl:for-each select=\"plist/dict/array/dict\">");
out << QString("<xsl:call-template name=\"playlistNames\"/>");
out << QString("</xsl:for-each>");
out << QString("</xsl:template>");
out << QString("</xsl:stylesheet>");
inFile.close();
return;
}
void ItunesLibParser::dumpPlayList()
{
QXmlQuery query(QXmlQuery::XSLT20);
query.setFocus(QUrl(pathToLib));
QFile xslFile("plist.xsl");
createXSLFile(xslFile);
query.setQuery(QUrl("plist.xsl"));
QStringList* outDump = new QStringList();
query.evaluateTo(outDump);
if(outDump != NULL) {
QStringList::iterator iter = (*outDump).begin();
for (; iter != (*outDump).end();
++iter)
//code flow doesn't come here. It means being() == end()
std::cout << (*iter).toLocal8Bit().constData() << std::endl;
}
return;
}
OutDump here doesn't contain data. While in Shell (xmlpatterns-4.7 mystlye.xsl itunes_music_library.xml ), If I run my Query I get proper output.
Is there anything, wrong I am doing while calling it programatically? I checked out plist.xsl is created properly, but my doubt is whether "/Users/rakesh/temp/itunes_xslt/itunes_music_library.xml" this is getting loaded or not? Or there might be another reasons, I am confused. Is there any experts to throw some light onto problem, I will be glad.
Intead from reading from the file, I read the file into buffer and converted that int string as passed to setquery. That solved the problem.
Here's sample code for those who could face similar problem in future.
void ITunesMlibParser::parsePlayListItemXml(int plistId)
{
QXmlQuery xQuery(QXmlQuery::XSLT20);
QFile inFile("/Users/rakesh/temp/itunes_xslt/itunes_music_library.xml");
if (!inFile.open(QIODevice::ReadOnly)) {
return;
}
QByteArray bArray;
while (!inFile.atEnd()) {
bArray += inFile.readLine();
}
QBuffer xOriginalContent(&bArray);
xOriginalContent.open(QBuffer::ReadWrite);
xOriginalContent.reset();
if (xQuery.setFocus(&xOriginalContent))
std::cout << "File Loaded" << std::endl;
//..
//..
}
Thanks
Rakesh
I am using the QJson for parsing. But I am stuck up with some issues. I have used the following code:
void CityBook ::getCityList(QUrl url)
{
//!connect(cityReply, SIGNAL(readyRead()),this, SLOT(httpReadyRead()));
cityGuideNetworkAccessManager = new QNetworkAccessManager(this);
connect(cityGuideNetworkAccessManager, SIGNAL(finished(QNetworkReply*)),
this, SLOT(httpReadyRead(QNetworkReply*)));
QNetworkRequest cityRequest(url);
cityGuideNetworkAccessManager->get(cityRequest);
}
void CityBook::httpReadyRead(QNetworkReply *reply)
{
QMessageBox::information(this, tr("HTTP"),
tr(reply->readAll()),QMessageBox::NoButton
);
QJson::Parser parser;
bool ok;
const QByteArray &resultbyte = reply->readAll();
qDebug() << resultbyte;
QVariant result1 = parser.parse(reply->readAll(), &ok);
qDebug() << result1;
QVariantList result=parser.parse(resultbyte,&ok).toList();
qDebug()<< result.size();
if (!ok)
{
qFatal("An error occurred during parsing");
exit (1);
}
qDebug() <<"error String"<< parser.errorString();
qDebug() <<"error" <parser.errorLine();
//! QVariantList entries = result["name"].toList();
foreach (QVariant city, result) {
QVariantMap names = city.toMap();
qDebug() << "\t-" << names.value("name");
}
}
The output is:
Starting /Users/QT Developement/CityBook-build-desktop/CityBook.app/Contents/MacOS/CityBook...
""
QVariant(, )
0
error String ""
error 0
The result of the readAll function is an empty byte array. According to documentation this can mean either that no data are available or that an error occurred.