×
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
NegInfinity (Talk | contribs)
hamishwillee (Talk | contribs)
m (Text replace - "<code cpp>" to "<code cpp-qt>")
 
(16 intermediate revisions by 3 users not shown)
Line 1: Line 1:
[[Category:Qt]][[Category:UI]]
+
[[Category:Qt]][[Category:UI]][[Category:Code Snippet]][[Category:MeeGo Harmattan]][[Category:Symbian]][[Category:Qt Quick]]
{{ReviewerApproved|timestamp=20090928}}
+
{{Abstract|This code snippet shows how to calculate hash for a text string using {{Qapiname|QCryptographicHash}}. }}
{{ArticleMetaData
+
|id=...
+
|platform=S60 3rd Edition FP1, S60 3rd Edition FP2, S60 5th Edition
+
|devices= S60 Emulator
+
|category=Qt
+
|subcategory=UI
+
|creationdate=10 April 2009
+
|keywords=QCryptographicHash
+
  
|sourcecode= <!-- Link to example source code (e.g. [[Media:The Code Example ZIP.zip]]) -->
+
{{ArticleMetaData <!-- v1.2 -->
 +
|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]]) -->
|sdk=<!-- SDK(s) built and tested against (e.g. [http://linktosdkdownload/ Nokia Qt SDK 1.1]) -->
+
|devices= Nokia C5-00S60, Emulator, Simulator
|devicecompatability=<!-- Compatible devices (e.g.: All* (must have GPS) ) -->
+
|sdk= [http://www.developer.nokia.com/info/sw.nokia.com/id/da8df288-e615-443d-be5c-00c8a72435f8/Qt_SDK.html Qt SDK 1.1.3]
|signing=<!-- Empty or one of Self-Signed, DevCert, Manufacturer -->
+
|platform= S60 3rd Edition FP1, S60 3rd Edition FP2, S60 5th Edition, Symbian^3,  Qt 4.6, Qt 4.7
|capabilities=<!-- Capabilities required (e.g. Location, NetworkServices. -->)
+
|devicecompatability= All which support Qt
|author=[[User:Mind freak]]
+
|dependencies= <!-- Any other/external dependencies e.g.: Google Maps Api v1.0 -->
 +
|signing= <!-- Empty or one of Self-Signed, DevCert, Manufacturer -->
 +
|capabilities= <!-- Capabilities required by the article/code example (e.g. Location, NetworkServices. -->
 +
|keywords= QCryptographicHash
 +
|language= <!-- Language category code for non-English topics - e.g. Lang-Chinese -->
 +
|translated-by= <!-- [[User:XXXX]] -->
 +
|translated-from-title= <!-- Title only -->
 +
|translated-from-id= <!-- Id of translated revision -->
 +
|review-by= [[User:NegInfinity]]
 +
|review-timestamp= 20110915
 +
|update-by=  [[User:vineet.jain]]
 +
|update-timestamp=  20120224
 +
|creationdate= 20090410
 +
|author= [[User:Mind freak]]
 
}}
 
}}
  
== Introduction ==
 
{{Abstract|visible=true|This example shows how to calculate hash for a text string using  [http://doc.qt.nokia.com/stable/qcryptographichash.html QCryptographicHash]. }}
 
  
==Preconditions==
+
== Source Code ==
  
* Download and install the [[Qt SDK]]
+
===Main.cpp===
 +
<code cpp-qt>
 +
#include <QtGui/QApplication>
 +
#include "qmlapplicationviewer.h"
 +
#include <QCryptographicHash>
 +
#include "QDeclarativeContext"
 +
#include "hashcalculate.h"
  
 +
int main(int argc, char *argv[])
 +
{
 +
    QApplication app(argc, argv);
  
== Some Related Function ==
+
    HashCalculate*ihashcalc = new HashCalculate();
*Adds the data to the cryptographic hash:
+
    QmlApplicationViewer viewer;
+
    viewer.setOrientation(QmlApplicationViewer::ScreenOrientationAuto);
QByteArray string = "Nokia";
+
    QDeclarativeContext *ctxt = viewer.rootContext();
QCryptographicHash hasher(QCryptographicHash::Sha1);
+
    ctxt->setContextProperty("myContextProperty",ihashcalc);
hasher.addData(string);
+
    viewer.setMainQmlFile(QLatin1String("qml/MD4HashSample/main.qml"));
 +
    viewer.showExpanded();
 +
    return app.exec();
 +
}
 +
</code>
  
*Returns the final hash value.
+
hashcalculate.cpp
  
QByteArray string1=hasher.result();
+
<code cpp-qt>
 +
#include "hashcalculate.h"
 +
#include <QCryptographicHash>
 +
#include "QDebug"
 +
HashCalculate::HashCalculate(QObject *parent) :
 +
    QObject(parent)
 +
{
 +
    iHashValue = "";
 +
}
  
== Source Code ==
+
void HashCalculate::calculateHash(const QString& aOriginalText )
 +
{
 +
QCryptographicHash hash(QCryptographicHash::Md4);
 +
hash.addData(aOriginalText.toUtf8());
 +
SetHash(QString(hash.result().toHex()));
 +
//qDebug() << QString(hash.result().toHex());
 +
}
  
===Main.cpp===
+
void HashCalculate::SetHash(const QString& aHashValue)
<code cpp>
+
{
#include <QtGui/QApplication>
+
iHashValue = aHashValue;
#include <QWidget>
+
}
#include <QHBoxLayout>
+
#include <QCryptographicHash>
+
#include <QString>
+
#include <QByteArray>
+
#include <QLineEdit>
+
#include <QLabel>
+
#include <QGridLayout>
+
#include <QPushButton>
+
#include <QHBoxLayout>
+
#include "hash.h"
+
  
int main(int argc, char **argv){
+
QString HashCalculate::getHash()
QApplication app(argc, argv);
+
{
 +
return iHashValue;
 +
}
 +
</code>
  
QWidget mainWindow;
+
hashcalculate.h
QGridLayout* layout=new QGridLayout();
+
  
//widget initialization
+
<code cpp-qt>
QLineEdit *hashTextEdit=new QLineEdit(),
+
#ifndef HASHCALCULATE_H
*originalTextEdit = new QLineEdit();
+
#define HASHCALCULATE_H
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
+
#include <QObject>
layout->addWidget(originalTextLabel, 0, 0);
+
layout->addWidget(originalTextEdit, 0, 1);
+
layout->addWidget(hashLabel, 1, 0);
+
layout->addWidget(hashTextEdit, 1, 1);
+
  
//bottom layout initialization ("close" button)
+
class HashCalculate : public QObject
QHBoxLayout* bottomLayout = new QHBoxLayout();
+
{
bottomLayout->addStretch();
+
    Q_OBJECT
QPushButton* closeButton = new QPushButton(QObject::tr("C&lose"));
+
public:
bottomLayout->addWidget(closeButton);
+
    explicit HashCalculate(QObject *parent = 0);
bottomLayout->addStretch();
+
    Q_INVOKABLE void calculateHash(const QString& aOriginalText );
bottomLayout->setMargin(0);
+
  
layout->addLayout(bottomLayout, 2, 0, 1, 2);
+
signals:
  
QObject::connect(closeButton, SIGNAL(clicked()), &mainWindow, SLOT(close()));
+
public slots:
 +
      QString getHash();
 +
      void SetHash(const QString& aHashValue);
 +
public:
 +
      QString iHashValue;
  
mainWindow.setLayout(layout);
+
};
  
//actual hash calculation TODO: make proper widget with signal/slots for hash calculation
+
#endif // HASHCALCULATE_H
QCryptographicHash hash(QCryptographicHash::Md4);
+
</code>
hash.addData(originalTextEdit->text().toUtf8());
+
hashTextEdit->setText(QString(hash.result().toHex()));
+
  
mainWindow.showMaximized();
+
Main.qml
      
+
 
return app.exec();
+
<code cpp-qt>
 +
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"))
 +
    }
 
}
 
}
 +
 
</code>
 
</code>
  
[[Category:Code Examples]]
+
MainPage.qml
==ScreenShot==
+
 
 +
<code cpp-qt>
 +
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]]
 +
 
 +
== About the Update ==
 +
 
 +
The implementation has now been converted using the Qt Quick components.As compared with the previous functionality in which a hard-coded text was getting converted into a hash, now the user has flexibility to enter any text & convert it into a hash code as visible in the screenshots.
 +
 
 +
== Source Code ==
  
[[Image:hash.png]]
+
Full source code can be downloaded from here : [[Media:MD4HashSample.zip]]
 +
<!-- Translation --> [[pt:Como criptografar um texto usando QCryptographicHash, em Qt]]

Latest revision as of 04:17, 11 October 2012

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

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: hamishwillee (11 Oct 2012)


Contents

[edit] Source Code

[edit] 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 = ""
}
}
 
}

[edit] ScreenShots

MD4HashBlank.jpg MD4Hashenter.jpg MD4Hash1.jpg

[edit] About the Update

The implementation has now been converted using the Qt Quick components.As compared with the previous functionality in which a hard-coded text was getting converted into a hash, now the user has flexibility to enter any text & convert it into a hash code as visible in the screenshots.

[edit] Source Code

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

This page was last modified on 11 October 2012, at 04:17.
284 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.

×