×
Namespaces

Variants
Actions
(Difference between revisions)

How to calculate hash for a text using QCryptographicHash in Qt

From Nokia Developer Wiki
Jump to: navigation, search
hamishwillee (Talk | contribs)
m (Hamishwillee - Fix typo)
vineet.jain (Talk | contribs)
(Vineet.jain -)
Line 3: Line 3:
 
{{ArticleNeedsUpdate|timestamp=20120209053618|user=[[User:Hamishwillee|<br />----]]|Needs to remove the QWidget based UI components of this article as Qt Quick is now recommended.}}
 
{{ArticleNeedsUpdate|timestamp=20120209053618|user=[[User:Hamishwillee|<br />----]]|Needs to remove the QWidget based UI components of this article as Qt Quick is now recommended.}}
 
{{ArticleMetaData <!-- v1.2 -->
 
{{ArticleMetaData <!-- v1.2 -->
|sourcecode= <!-- Link to example source code (e.g. [[Media:The Code Example ZIP.zip]]) -->
+
|sourcecode= [[Media:MD4HashSample.zip]])  
 
|installfile= <!-- Link to installation file (e.g. [[Media:The Installation File.sis]]) -->
 
|installfile= <!-- Link to installation file (e.g. [[Media:The Installation File.sis]]) -->
 
|devices= Nokia C5-00S60, Emulator, Simulator
 
|devices= Nokia C5-00S60, Emulator, Simulator
Line 19: Line 19:
 
|review-by= [[User:NegInfinity]]
 
|review-by= [[User:NegInfinity]]
 
|review-timestamp= 20110915
 
|review-timestamp= 20110915
|update-by= <!-- After significant update: [[User:username]]-->
+
|update-by= [[User:vineet.jain]]
|update-timestamp= <!-- After significant update: YYYYMMDD -->
+
|update-timestamp= 20120224
 
|creationdate= 20090410
 
|creationdate= 20090410
 
|author= [[User:Mind freak]]
 
|author= [[User:Mind freak]]
 
}}
 
}}
  
== Important functions ==
 
*Adds the data to the cryptographic hash:
 
  
<code cpp>
 
QByteArray string = "Nokia";
 
QCryptographicHash hasher(QCryptographicHash::Sha1);
 
hasher.addData(string);
 
</code>
 
*Returns the final hash value.
 
<code cpp>
 
QByteArray string1=hasher.result();
 
</code>
 
 
== Source Code ==
 
== Source Code ==
  
Line 42: Line 31:
 
<code cpp>
 
<code cpp>
 
#include <QtGui/QApplication>
 
#include <QtGui/QApplication>
#include <QWidget>
+
#include "qmlapplicationviewer.h"
#include <QHBoxLayout>
+
 
#include <QCryptographicHash>
 
#include <QCryptographicHash>
#include <QString>
+
#include "QDeclarativeContext"
#include <QByteArray>
+
#include "hashcalculate.h"
#include <QLineEdit>
+
#include <QLabel>
+
#include <QGridLayout>
+
#include <QPushButton>
+
#include <QHBoxLayout>
+
  
int main(int argc, char **argv){
+
int main(int argc, char *argv[])
QApplication app(argc, argv);
+
{
 +
    QApplication app(argc, argv);
  
QWidget mainWindow;
+
    HashCalculate*ihashcalc =  new HashCalculate();
QGridLayout* layout=new QGridLayout();
+
    QmlApplicationViewer viewer;
 +
    viewer.setOrientation(QmlApplicationViewer::ScreenOrientationAuto);
 +
    QDeclarativeContext *ctxt = viewer.rootContext();
 +
    ctxt->setContextProperty("myContextProperty",ihashcalc);
 +
    viewer.setMainQmlFile(QLatin1String("qml/MD4HashSample/main.qml"));
 +
    viewer.showExpanded();
 +
    return app.exec();
 +
}
 +
</code>
  
//widget initialization
+
hashcalculate.cpp
QLineEdit *hashTextEdit=new QLineEdit(),
+
*originalTextEdit = new QLineEdit();
+
originalTextEdit->setReadOnly(true);
+
originalTextEdit->setText(QObject::tr("Nokia"));
+
hashTextEdit->setReadOnly(true);
+
QLabel *hashLabel=new QLabel(QObject::tr("MD4 &Hash:")),
+
*originalTextLabel = new QLabel(QObject::tr("Original &Text:"));
+
hashLabel->setBuddy(hashTextEdit);
+
originalTextLabel->setBuddy(originalTextEdit);
+
  
//widget placement
+
<code cpp>
layout->addWidget(originalTextLabel, 0, 0);
+
#include "hashcalculate.h"
layout->addWidget(originalTextEdit, 0, 1);
+
#include <QCryptographicHash>
layout->addWidget(hashLabel, 1, 0);
+
#include "QDebug"
layout->addWidget(hashTextEdit, 1, 1);
+
HashCalculate::HashCalculate(QObject *parent) :
 +
    QObject(parent)
 +
{
 +
    iHashValue = "";
 +
}
  
//bottom layout initialization ("close" button)
+
void HashCalculate::calculateHash(const QString& aOriginalText )
QHBoxLayout* bottomLayout = new QHBoxLayout();
+
{
bottomLayout->addStretch();
+
QCryptographicHash hash(QCryptographicHash::Md4);
QPushButton* closeButton = new QPushButton(QObject::tr("C&lose"));
+
hash.addData(aOriginalText.toUtf8());
bottomLayout->addWidget(closeButton);
+
SetHash(QString(hash.result().toHex()));
bottomLayout->addStretch();
+
//qDebug() << QString(hash.result().toHex());
bottomLayout->setMargin(0);
+
}
  
layout->addLayout(bottomLayout, 2, 0, 1, 2);
+
void HashCalculate::SetHash(const QString& aHashValue)
 +
{
 +
iHashValue = aHashValue;
 +
}
  
QObject::connect(closeButton, SIGNAL(clicked()), &mainWindow, SLOT(close()));
+
QString HashCalculate::getHash()
 +
{
 +
return iHashValue;
 +
}
 +
</code>
  
mainWindow.setLayout(layout);
+
hashcalculate.h
  
//actual hash calculation TODO: make proper widget with signal/slots for hash calculation
+
<code cpp>
QCryptographicHash hash(QCryptographicHash::Md4);
+
#ifndef HASHCALCULATE_H
hash.addData(originalTextEdit->text().toUtf8());
+
#define HASHCALCULATE_H
hashTextEdit->setText(QString(hash.result().toHex()));
+
 
 +
#include <QObject>
 +
 
 +
class HashCalculate : public QObject
 +
{
 +
    Q_OBJECT
 +
public:
 +
    explicit HashCalculate(QObject *parent = 0);
 +
    Q_INVOKABLE void calculateHash(const QString& aOriginalText );
 +
 
 +
signals:
 +
 
 +
public slots:
 +
      QString getHash();
 +
      void SetHash(const QString& aHashValue);
 +
public:
 +
      QString iHashValue;
 +
 
 +
};
 +
 
 +
#endif // HASHCALCULATE_H
 +
</code>
 +
 
 +
Main.qml
 +
 
 +
<code cpp>
 +
import QtQuick 1.0
 +
import com.nokia.symbian 1.0
 +
 
 +
Window {
 +
    id: window
 +
 
 +
    StatusBar {
 +
        id: statusBar
 +
        anchors.top: window.top
 +
    }
 +
 
 +
    PageStack {
 +
        id: pageStack
 +
        anchors { left: parent.left; right: parent.right; top: statusBar.bottom; bottom: toolBar.top }
 +
    }
 +
 
 +
    ToolBar {
 +
        id: toolBar
 +
        anchors.bottom: window.bottom
 +
        tools: ToolBarLayout {
 +
            id: toolBarLayout
 +
            ToolButton {
 +
                flat: true
 +
                iconSource: "toolbar-back"
 +
                onClicked: pageStack.depth <= 1 ? Qt.quit() : pageStack.pop()
 +
            }
 +
        }
 +
    }
  
mainWindow.showMaximized();
+
    Component.onCompleted: {
   
+
        pageStack.push(Qt.resolvedUrl("MainPage.qml"))
return app.exec();
+
    }
 
}
 
}
 +
 
</code>
 
</code>
  
==ScreenShot==
+
MainPage.qml
 +
 
 +
<code cpp>
 +
import QtQuick 1.0
 +
import com.nokia.symbian 1.0
 +
 
 +
Page {
 +
    id: mainPage
 +
 
 +
    Text {
 +
        text: qsTr("Enter Text:")
 +
        id:textorg
 +
        color: platformStyle.colorNormalLight
 +
        font.pixelSize: 20
 +
        x:text_originaltxt.x
 +
        y:text_originaltxt.y-45
 +
    }
 +
 
 +
    Text {
 +
        text: qsTr("MD4 Hash :")
 +
        id: txthshd
 +
        color: platformStyle.colorNormalLight
 +
        font.pixelSize: 20
 +
        x:text_hashedtxt.x
 +
        y:text_hashedtxt.y-40
 +
 
 +
    }
 +
 
 +
    TextField {
 +
        id: text_originaltxt
 +
        x: parent.x+5
 +
        y:parent.y+55
 +
        width: parent.width-15
 +
        text : "Nokia"
 +
 
 +
    }
 +
    TextField {
 +
        id: text_hashedtxt
 +
        x: text_originaltxt.x
 +
        y:text_originaltxt.y+110
 +
        width: parent.width-15
 +
        readOnly: true
 +
        text : ""
 +
 
 +
    }
 +
 
 +
    Button {
 +
            id: btnhash
 +
            x:parent.x+50
 +
            y:text_hashedtxt.y+text_hashedtxt.height+txthshd.height+5
 +
            text: "Get Hash"
 +
            onClicked: {
 +
                myContextProperty.calculateHash(text_originaltxt.text)
 +
                text_hashedtxt.text = myContextProperty.getHash()
 +
            }
 +
        }
 +
    Button {
 +
            id: btnclr
 +
            x:parent.x+btnhash.width+130
 +
            y:text_hashedtxt.y+text_hashedtxt.height+txthshd.height+5
 +
            text: "Clear"
 +
            onClicked: {
 +
                text_originaltxt.text = ""
 +
                text_hashedtxt.text = ""
 +
            }
 +
        }
 +
 
 +
}
 +
 
 +
</code>
 +
==ScreenShots==
 +
 
 +
[[File:MD4HashBlank.jpg]]  [[File:MD4Hashenter.jpg]]  [[File:MD4Hash1.jpg]]
 +
 
 +
== Source Code ==
  
[[File:hash.png]]
+
Full source code can be downloaded from here : [[Media:MD4HashSample.zip]]

Revision as of 15:34, 24 February 2012

This code snippet shows how to calculate hash for a text string using QCryptographicHash.

Needs-update.pngThis article needs to be updated: If you found this article useful, please fix the problems below then delete the {{ArticleNeedsUpdate}} template from the article to remove this warning.

Reasons: hamishwillee (09 Feb 2012)
Needs to remove the QWidget based UI components of this article as Qt Quick is now recommended.

Article Metadata
Code ExampleTested with
Devices(s): Nokia C5-00S60, Emulator, Simulator
Compatibility
Platform(s): S60 3rd Edition FP1, S60 3rd Edition FP2, S60 5th Edition, Symbian^3, Qt 4.6, Qt 4.7
Symbian
Device(s): All which support Qt
Article
Keywords: QCryptographicHash
Created: mind_freak (10 Apr 2009)
Updated: vineet.jain (24 Feb 2012)
Reviewed: NegInfinity (15 Sep 2011)
Last edited: vineet.jain (24 Feb 2012)


Contents

Source Code

Main.cpp

#include <QtGui/QApplication>
#include "qmlapplicationviewer.h"
#include <QCryptographicHash>
#include "QDeclarativeContext"
#include "hashcalculate.h"
 
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
 
HashCalculate*ihashcalc = new HashCalculate();
QmlApplicationViewer viewer;
viewer.setOrientation(QmlApplicationViewer::ScreenOrientationAuto);
QDeclarativeContext *ctxt = viewer.rootContext();
ctxt->setContextProperty("myContextProperty",ihashcalc);
viewer.setMainQmlFile(QLatin1String("qml/MD4HashSample/main.qml"));
viewer.showExpanded();
return app.exec();
}

hashcalculate.cpp

#include "hashcalculate.h"
#include <QCryptographicHash>
#include "QDebug"
HashCalculate::HashCalculate(QObject *parent) :
QObject(parent)
{
iHashValue = "";
}
 
void HashCalculate::calculateHash(const QString& aOriginalText )
{
QCryptographicHash hash(QCryptographicHash::Md4);
hash.addData(aOriginalText.toUtf8());
SetHash(QString(hash.result().toHex()));
//qDebug() << QString(hash.result().toHex());
}
 
void HashCalculate::SetHash(const QString& aHashValue)
{
iHashValue = aHashValue;
}
 
QString HashCalculate::getHash()
{
return iHashValue;
}

hashcalculate.h

#ifndef HASHCALCULATE_H
#define HASHCALCULATE_H
 
#include <QObject>
 
class HashCalculate : public QObject
{
Q_OBJECT
public:
explicit HashCalculate(QObject *parent = 0);
Q_INVOKABLE void calculateHash(const QString& aOriginalText );
 
signals:
 
public slots:
QString getHash();
void SetHash(const QString& aHashValue);
public:
QString iHashValue;
 
};
 
#endif // HASHCALCULATE_H

Main.qml

import QtQuick 1.0
import com.nokia.symbian 1.0
 
Window {
id: window
 
StatusBar {
id: statusBar
anchors.top: window.top
}
 
PageStack {
id: pageStack
anchors { left: parent.left; right: parent.right; top: statusBar.bottom; bottom: toolBar.top }
}
 
ToolBar {
id: toolBar
anchors.bottom: window.bottom
tools: ToolBarLayout {
id: toolBarLayout
ToolButton {
flat: true
iconSource: "toolbar-back"
onClicked: pageStack.depth <= 1 ? Qt.quit() : pageStack.pop()
}
}
}
 
Component.onCompleted: {
pageStack.push(Qt.resolvedUrl("MainPage.qml"))
}
}

MainPage.qml

import QtQuick 1.0
import com.nokia.symbian 1.0
 
Page {
id: mainPage
 
Text {
text: qsTr("Enter Text:")
id:textorg
color: platformStyle.colorNormalLight
font.pixelSize: 20
x:text_originaltxt.x
y:text_originaltxt.y-45
}
 
Text {
text: qsTr("MD4 Hash :")
id: txthshd
color: platformStyle.colorNormalLight
font.pixelSize: 20
x:text_hashedtxt.x
y:text_hashedtxt.y-40
 
}
 
TextField {
id: text_originaltxt
x: parent.x+5
y:parent.y+55
width: parent.width-15
text : "Nokia"
 
}
TextField {
id: text_hashedtxt
x: text_originaltxt.x
y:text_originaltxt.y+110
width: parent.width-15
readOnly: true
text : ""
 
}
 
Button {
id: btnhash
x:parent.x+50
y:text_hashedtxt.y+text_hashedtxt.height+txthshd.height+5
text: "Get Hash"
onClicked: {
myContextProperty.calculateHash(text_originaltxt.text)
text_hashedtxt.text = myContextProperty.getHash()
}
}
Button {
id: btnclr
x:parent.x+btnhash.width+130
y:text_hashedtxt.y+text_hashedtxt.height+txthshd.height+5
text: "Clear"
onClicked: {
text_originaltxt.text = ""
text_hashedtxt.text = ""
}
}
 
}

ScreenShots

MD4HashBlank.jpg MD4Hashenter.jpg MD4Hash1.jpg

Source Code

Full source code can be downloaded from here : Media:MD4HashSample.zip

302 page views in the last 30 days.

Was this page helpful?

Your feedback about this content is important. Let us know what you think.

 

Thank you!

We appreciate your feedback.

×