Qt wiki will be updated on October 12th 2023 starting at 11:30 AM (EEST) and the maintenance will last around 2-3 hours. During the maintenance the site will be unavailable.

Simple encryption: Difference between revisions

From Qt Wiki
Jump to navigation Jump to search
No edit summary
No edit summary
Line 1: Line 1:
[[Category:Snippets]]


[toc align_right="yes" depth="2"]
= Simple encryption with SimpleCrypt =
Sometimes, you have to store some information that you may want to protect against casual observation. Think about passwords for remote services, for instance. Strong cryptography is obviously the best solution, but it can be hard to use those in the right way, they tend to pull in more libraries, and frankly, it may just be overkill for the situation.
* Note: additional details are available in [[SimpleCrypt_algorithm_details]]
* Note: a usage example can be found here [[Simple_Crypt_IO_Device]]
== A word of warning ==
==== The class presented in this article does ''not'' provide strong encryption! ====
It will protect your data from casual observers, but it will not stand up to dedicated hackers trying to break your secrets. I am not a cryptography expert. Use the code here at your own risk. I am not to be held responsible for any damages that may, directly or indirectly, happen because of your use of this code. Don't say you were not warned.
== Introducing SimpleCrypt ==
The idea of <code>SimpleCrypt</code> is to provide some basic cryptographic capabilities for simple encryption. Only symmetric encryption is supported (that is: only with the same key for encryption and decryption), and there is no API for streaming data in and out like you often see with more advanced cyphers. If you need stronger cryptography, streaming cyphers or asymmetric keys, take a look at "QCA":http://delta.affinix.com/qca/ instead.
The <code>SimpleCrypt</code> class takes a 64 bits key in the form of a quint64. If you use a fixed key build into your program, you can do something like this to initialize your <code>SimpleCrypt</code> object:
<code><br />SimpleCrypt crypto(Q_UINT64_C(0x0c2ad4a4acb9f023)); //some random number<br />…<br /></code><br />You can also use the &lt;code&amp;gt;setKey()&lt;/code&amp;gt; method to set a key on the class.
=== Selecting a suitable key ===
To get such random numbers, you might use &quot;this service&amp;quot;:http://www.random.org/integers/?num=10&amp;amp;min=0&amp;amp;max=65535&amp;amp;col=5&amp;amp;base=16&amp;amp;format=html&amp;amp;rnd=new and pick four of the 2 byte hexadecimals that you concatenate together as done above. That works better than trying to make up something semi-random yourself. Of course, you can also use other means to get to a quint64 key, such as using some hash of a password and reducing that to 64 bits.
=== SimpleCrypt in use ===
Once setup, you can use &lt;code&amp;gt;SimpleCrypt&amp;lt;/code&amp;gt; to actually encrypt or decrypt data. For the encrypt functions, both the ''plaintext'' that you input as the ''cyphertext'' that is being outputted can be either a &lt;code&amp;gt;QString&amp;lt;/code&amp;gt; or a &lt;code&amp;gt;QByteArray&amp;lt;/code&amp;gt;. The reverse applies to the decrypt functions. That results in four encrypt methods, and four corresponding decrypt methods:
===== Encryption methods =====
* &lt;code&amp;gt;QString encryptToString(const QString&amp;amp; plaintext)&lt;/code&amp;gt;
* &lt;code&amp;gt;QString encryptToString(QByteArray plaintext)&lt;/code&amp;gt;
* &lt;code&amp;gt;QByteArray encryptToByteArray(const QString&amp;amp; plaintext)&lt;/code&amp;gt;
* &lt;code&amp;gt;QByteArray encryptToByteArray(QByteArray plaintext)&lt;/code&amp;gt;
===== Decryption methods =====
* &lt;code&amp;gt;QString decryptToString(const QString&amp;amp; plaintext)&lt;/code&amp;gt;
* &lt;code&amp;gt;QString decryptToString(QByteArray plaintext)&lt;/code&amp;gt;
* &lt;code&amp;gt;QByteArray decryptToByteArray(const QString&amp;amp; plaintext)&lt;/code&amp;gt;
* &lt;code&amp;gt;QByteArray decryptToByteArray(QByteArray plaintext)&lt;/code&amp;gt;
==== Use with QStrings ====
<code><br /> SimpleCrypt crypto(Q_UINT64_C(0x0c2ad4a4acb9f023)); //some random number<br /> QString testString(&quot;Lorem ipsum dolor sit amet, consectetur adipiscing elit.&quot;);<br /> QString result = crypto.encryptToString(testString);<br /> QString decrypted = crypto.decryptToString(result);<br /> qDebug() &lt;&lt; testString &lt;&lt; endl &lt;&lt; result &lt;&lt; endl &lt;&lt; decrypted;<br /></code>
The code above encrypts a &lt;code&amp;gt;QString&amp;lt;/code&amp;gt; to a &lt;code&amp;gt;QString&amp;lt;/code&amp;gt;, and then decrypts that string again to a new &lt;code&amp;gt;QString&amp;lt;/code&amp;gt;.
==== Use with binary data ====
If you want to encrypt your own binary data, you might do something like this:
<code><br /> //setup our objects<br /> SimpleCrypt crypto(Q_UINT64_C(0x0c2ad4a4acb9f023)); //some random number<br /> crypto.setCompressionMode(SimpleCrypt::CompressionAlways); //always compress the data, see section below<br /> crypto.setIntegrityProtectionMode(SimpleCrypt::ProtectionHash); //properly protect the integrity of the data<br /> QBuffer buffer;<br /> buffer.open(QIODevice::WriteOnly);<br /> QDataStream s(&amp;buffer);<br /> //stream the data into our buffer<br /> s.setVersion(QDataStream::Qt_4_7);<br /> s &lt;&lt; myString; //stream in a string<br /> s &lt;&lt; myUint16; //stream in an unsigned integer<br /> s &lt;&lt; myImage; //stream in an image<br /> s &lt;&lt; someMoreData;<br /> // … etc.
QByteArray myCypherText = crypto.encryptToByteArray(buffer.data());<br /> if (crypto.lastError() == SimpleCrypt::ErrorNoError) {<br /> // do something relevant with the cyphertext, such as storing it or sending it over a socket to another machine.<br /> }<br /> buffer.close();<br /></code>
Note the use of the data protection feature. I would recommend that you use at least the &lt;code&amp;gt;ProtectionChecksum&amp;lt;/code&amp;gt; level of protection (enabled by default) if you work with binary data, as streaming invalid binary data into your program can lead to big problems.
On the other end, you can now do:<br /><code><br /> SimpleCrypt crypto(Q_UINT64_C(0x0c2ad4a4acb9f023)); //same random number: key should match encryption key<br /> QByteArray plaintext = crypto.decryptToByteArray(myCypherText);<br /> if (!crypto.lastError() == SimpleCrypt::ErrorNoError) {<br /> // check why we have an error, use the error code from crypto.lastError() for that<br /> return;<br /> }
QBuffer buffer(&amp;plaintext);<br /> buffer.open(QIODevice::ReadOnly);<br /> QDataStream s(&amp;buffer);<br /> s.setVersion(QDataStream::Qt_4_7);<br /> s &gt;&gt; myString; //stream in a string<br /> s &gt;&gt; myUint16; //stream in an unsigned integer<br /> s &gt;&gt; myImage; //stream in an image<br /> s &gt;&gt; someMoreData;<br /> //etc.
buffer.close();<br /></code>
The code above might crash if the integrity of the data is not guaranteed, for instance by the use of a wrong password. Using the highest level of protection is probably OK here, as we have quite a big blob of data already, so adding the overhead of adding a 20 byte SHA1 cryptographic hash is justifiable.
== Compression ==
For long strings, it can be beneficial to use compression before encryption. Not only does the length of the string decrease, the input will be a bit more random-looking too, resulting in a harder to break cyphertext (at least, in principle, see the warning at the top of this page.) However, for short strings, applying compression can lead to an ''increase'' in the string length.
&lt;code&amp;gt;SimpleCrypt&amp;lt;/code&amp;gt; supports three modes for compression before encryption. You can force to always use compression, to never use compression, or to automatically choose the shortest version (either the compressed one or the uncompressed one). The last option is the default option. Note that setting this only affects ''encryption''. For decryption, &lt;code&amp;gt;SimpleCrypt&amp;lt;/code&amp;gt; automatically decompresses the data if compression was used for the encryption.
== The code ==
simplecrypt.h<br /><code><br />/*<br />Copyright © 2011, Andre Somers<br />All rights reserved.
Redistribution and use in source and binary forms, with or without<br />modification, are permitted provided that the following conditions are met:<br /> * Redistributions of source code must retain the above copyright<br /> notice, this list of conditions and the following disclaimer.<br /> * Redistributions in binary form must reproduce the above copyright<br /> notice, this list of conditions and the following disclaimer in the<br /> documentation and/or other materials provided with the distribution.<br /> * Neither the name of the Rathenau Instituut, Andre Somers nor the<br /> names of its contributors may be used to endorse or promote products<br /> derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS &quot;AS IS&amp;quot; AND<br />ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED<br />WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE<br />DISCLAIMED. IN NO EVENT SHALL ANDRE SOMERS BE LIABLE FOR ANY<br />DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES<br />(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;<br />LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND<br />ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT<br />(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS<br />SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.<br />'''/
<br />#ifndef SIMPLECRYPT_H<br />#define SIMPLECRYPT_H<br />#include &lt;QString&amp;gt;<br />#include &lt;QVector&amp;gt;<br />#include &lt;QFlags&amp;gt;
<br />/'''*<br /> </code>short Simple encryption and decryption of strings and byte arrays
This class provides a simple implementation of encryption and decryption<br /> of strings and byte arrays.
<code>warning The encryption provided by this class is NOT strong encryption. It may<br /> help to shield things from curious eyes, but it will NOT stand up to someone<br /> determined to break the encryption. Don't say you were not warned.
The class uses a 64 bit key. Simply create an instance of the class, set the key,<br /> and use the encryptToString() method to calculate an encrypted version of the input string.<br /> To decrypt that string again, use an instance of SimpleCrypt initialized with<br /> the same key, and call the decryptToString() method with the encrypted string. If the key<br /> matches, the decrypted version of the string will be returned again.
If you do not provide a key, or if something else is wrong, the encryption and<br /> decryption function will return an empty string or will return a string containing nonsense.<br /> lastError() will return a value indicating if the method was succesful, and if not, why not.
SimpleCrypt is prepared for the case that the encryption and decryption<br /> algorithm is changed in a later version, by prepending a version identifier to the cypertext.<br /> '''/<br />class SimpleCrypt<br />{<br />public:<br /> /'''*<br /> CompressionMode describes if compression will be applied to the data to be<br /> encrypted.<br /> '''/<br /> enum CompressionMode {<br /> CompressionAuto, /'''[[Image:&lt; Only apply compression if that results in a shorter plaintext. */
        CompressionAlways,  /*|]]&lt; Always apply compression. Note that for short inputs, a compression may result in longer data '''/<br /> CompressionNever /'''!&lt; Never apply compression. '''/<br /> };<br /> /'''*<br /> IntegrityProtectionMode describes measures taken to make it possible to detect problems with the data<br /> or wrong decryption keys.
Measures involve adding a checksum or a cryptograhpic hash to the data to be encrypted. This<br /> increases the length of the resulting cypertext, but makes it possible to check if the plaintext<br /> appears to be valid after decryption.<br /> '''/<br /> enum IntegrityProtectionMode {<br /> ProtectionNone, /'''[[Image:&lt; The integerity of the encrypted data is not protected. It is not really possible to detect a wrong key, for instance. */
        ProtectionChecksum,/*|]]&lt; A simple checksum is used to verify that the data is in order. If not, an empty string is returned. '''/<br /> ProtectionHash /'''[[Image:&lt; A cryptographic hash is used to verify the integrity of the data. This method produces a much stronger, but longer check */
    &#125;;
    /**
      Error describes the type of error that occured.
      */
    enum Error &#123;
        ErrorNoError,        /*|]]&lt; No error occurred. '''/<br /> ErrorNoKeySet, /'''[[Image:&lt; No key was set. You can not encrypt or decrypt without a valid key. */
        ErrorUnknownVersion,  /*|]]&lt; The version of this data is unknown, or the data is otherwise not valid. '''/<br /> ErrorIntegrityFailed, /'''!&lt; The integrity check of the data failed. Perhaps the wrong key was used. '''/<br /> };
<br /> /'''*<br /> Constructor.
Constructs a SimpleCrypt instance without a valid key set on it.<br /> '''/<br /> SimpleCrypt();<br /> /'''*<br /> Constructor.
Constructs a SimpleCrypt instance and initializes it with the given </code>arg key.<br /> '''/<br /> explicit SimpleCrypt(quint64 key);
<br /> /'''*<br /> (Re-) initializes the key with the given <code>arg key.<br /> '''/<br /> void setKey(quint64 key);<br /> /'''*<br /> Returns true if SimpleCrypt has been initialized with a key.<br /> '''/<br /> bool hasKey() const {return !m_keyParts.isEmpty();}
<br /> /'''*<br /> Sets the compression mode to use when encrypting data. The default mode is Auto.
Note that decryption is not influenced by this mode, as the decryption recognizes<br /> what mode was used when encrypting.<br /> '''/<br /> void setCompressionMode(CompressionMode mode) {m_compressionMode = mode;}<br /> /'''*<br /> Returns the CompressionMode that is currently in use.<br /> '''/<br /> CompressionMode compressionMode() const {return m_compressionMode;}
<br /> /'''*<br /> Sets the integrity mode to use when encrypting data. The default mode is Checksum.
Note that decryption is not influenced by this mode, as the decryption recognizes<br /> what mode was used when encrypting.<br /> '''/<br /> void setIntegrityProtectionMode(IntegrityProtectionMode mode) {m_protectionMode = mode;}<br /> /'''*<br /> Returns the IntegrityProtectionMode that is currently in use.<br /> '''/<br /> IntegrityProtectionMode integrityProtectionMode() const {return m_protectionMode;}
<br /> /'''*<br /> Returns the last error that occurred.<br /> '''/<br /> Error lastError() const {return m_lastError;}
<br /> /'''*<br /> Encrypts the </code>arg plaintext string with the key the class was initialized with, and returns<br /> a cyphertext the result. The result is a base64 encoded version of the binary array that is the<br /> actual result of the string, so it can be stored easily in a text format.<br /> '''/<br /> QString encryptToString(const QString&amp;amp; plaintext) ;<br /> /'''*<br /> Encrypts the <code>arg plaintext QByteArray with the key the class was initialized with, and returns<br /> a cyphertext the result. The result is a base64 encoded version of the binary array that is the<br /> actual result of the encryption, so it can be stored easily in a text format.<br /> '''/<br /> QString encryptToString(QByteArray plaintext) ;<br /> /'''*<br /> Encrypts the </code>arg plaintext string with the key the class was initialized with, and returns<br /> a binary cyphertext in a QByteArray the result.
This method returns a byte array, that is useable for storing a binary format. If you need<br /> a string you can store in a text file, use encryptToString() instead.<br /> '''/<br /> QByteArray encryptToByteArray(const QString&amp;amp; plaintext) ;<br /> /'''*<br /> Encrypts the <code>arg plaintext QByteArray with the key the class was initialized with, and returns<br /> a binary cyphertext in a QByteArray the result.
This method returns a byte array, that is useable for storing a binary format. If you need<br /> a string you can store in a text file, use encryptToString() instead.<br /> '''/<br /> QByteArray encryptToByteArray(QByteArray plaintext) ;
<br /> /'''*<br /> Decrypts a cyphertext string encrypted with this class with the set key back to the<br /> plain text version.
If an error occured, such as non-matching keys between encryption and decryption,<br /> an empty string or a string containing nonsense may be returned.<br /> '''/<br /> QString decryptToString(const QString&amp;amp; cyphertext) ;<br /> /'''*<br /> Decrypts a cyphertext string encrypted with this class with the set key back to the<br /> plain text version.
If an error occured, such as non-matching keys between encryption and decryption,<br /> an empty string or a string containing nonsense may be returned.<br /> '''/<br /> QByteArray decryptToByteArray(const QString&amp;amp; cyphertext) ;<br /> /'''*<br /> Decrypts a cyphertext binary encrypted with this class with the set key back to the<br /> plain text version.
If an error occured, such as non-matching keys between encryption and decryption,<br /> an empty string or a string containing nonsense may be returned.<br /> '''/<br /> QString decryptToString(QByteArray cypher) ;<br /> /'''*<br /> Decrypts a cyphertext binary encrypted with this class with the set key back to the<br /> plain text version.
If an error occured, such as non-matching keys between encryption and decryption,<br /> an empty string or a string containing nonsense may be returned.<br /> '''/<br /> QByteArray decryptToByteArray(QByteArray cypher) ;
<br /> //enum to describe options that have been used for the encryption. Currently only one, but<br /> //that only leaves room for future extensions like adding a cryptographic hash…<br /> enum CryptoFlag{CryptoFlagNone = 0,<br /> CryptoFlagCompression = 0x01,<br /> CryptoFlagChecksum = 0x02,<br /> CryptoFlagHash = 0x04<br /> };<br /> Q_DECLARE_FLAGS(CryptoFlags, CryptoFlag);<br />private:
<br /> void splitKey();
<br /> quint64 m_key;<br /> QVector&amp;lt;char&amp;gt; m_keyParts;<br /> CompressionMode m_compressionMode;<br /> IntegrityProtectionMode m_protectionMode;<br /> Error m_lastError;<br />};<br />Q_DECLARE_OPERATORS_FOR_FLAGS(SimpleCrypt::CryptoFlags)
<br />#endif // SimpleCrypt_H
<br /></code>
<br />simplecrypt.cpp<br /><code><br />/'''<br />Copyright © 2011, Andre Somers<br />All rights reserved.
Redistribution and use in source and binary forms, with or without<br />modification, are permitted provided that the following conditions are met:<br /> * Redistributions of source code must retain the above copyright<br /> notice, this list of conditions and the following disclaimer.<br /> * Redistributions in binary form must reproduce the above copyright<br /> notice, this list of conditions and the following disclaimer in the<br /> documentation and/or other materials provided with the distribution.<br /> * Neither the name of the Rathenau Instituut, Andre Somers nor the<br /> names of its contributors may be used to endorse or promote products<br /> derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS &quot;AS IS&amp;quot; AND<br />ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED<br />WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE<br />DISCLAIMED. IN NO EVENT SHALL ANDRE SOMERS BE LIABLE FOR ANY<br />DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES<br />(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;<br />LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND<br />ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT<br />(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS<br />SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.<br />'''/<br />#include &quot;simplecrypt.h&amp;quot;<br />#include &lt;QByteArray&amp;gt;<br />#include &lt;QtDebug&amp;gt;<br />#include &lt;QtGlobal&amp;gt;<br />#include &lt;QDateTime&amp;gt;<br />#include &lt;QCryptographicHash&amp;gt;
<br />SimpleCrypt::SimpleCrypt():<br /> m_key(0),<br /> m_compressionMode(CompressionAuto),<br /> m_protectionMode(ProtectionChecksum),<br /> m_lastError(ErrorNoError)<br />{<br /> qsrand(uint(QDateTime::currentMSecsSinceEpoch() &amp; 0xFFFF));<br />}
<br />SimpleCrypt::SimpleCrypt(quint64 key):<br /> m_key(key),<br /> m_compressionMode(CompressionAuto),<br /> m_protectionMode(ProtectionChecksum),<br /> m_lastError(ErrorNoError)<br />{<br /> qsrand(uint(QDateTime::currentMSecsSinceEpoch() &amp; 0xFFFF));<br /> splitKey();<br />}
<br />void SimpleCrypt::setKey(quint64 key)<br />{<br /> m_key = key;<br /> splitKey();<br />}
<br />void SimpleCrypt::splitKey()<br />{<br /> m_keyParts.clear();<br /> m_keyParts.resize(8);<br /> for (int i=0;i&amp;lt;8;i+'') {<br /> quint64 part = m_key;<br /> for (int j=i; j&amp;gt;0; j—)<br /> part = part &gt;&gt; 8;<br /> part = part &amp; 0xff;<br /> m_keyParts[i] = static_cast&amp;lt;char&amp;gt;(part);<br /> }<br />}
<br />QByteArray SimpleCrypt::encryptToByteArray(const QString&amp;amp; plaintext)<br />{<br /> QByteArray plaintextArray = plaintext.toUtf8();<br /> return encryptToByteArray(plaintextArray);<br />}
<br />QByteArray SimpleCrypt::encryptToByteArray(QByteArray plaintext)<br />{<br /> if (m_keyParts.isEmpty()) {<br /> qWarning() &lt;&lt; &quot;No key set.&quot;;<br /> m_lastError = ErrorNoKeySet;<br /> return QByteArray();<br /> }
<br /> QByteArray ba = plaintext;
<br /> CryptoFlags flags = CryptoFlagNone;<br /> if (m_compressionMode  CompressionAlways) &amp;#123;
        ba = qCompress(ba, 9); //maximum compression
        flags |= CryptoFlagCompression;
    &amp;#125; else if (m_compressionMode  CompressionAuto) {<br /> QByteArray compressed = qCompress(ba, 9);<br /> if (compressed.count() &lt; ba.count()) {<br /> ba = compressed;<br /> flags |= CryptoFlagCompression;<br /> }<br /> }
<br /> QByteArray integrityProtection;<br /> if (m_protectionMode  ProtectionChecksum) &amp;#123;
        flags |= CryptoFlagChecksum;
        QDataStream s(&amp;amp;integrityProtection, QIODevice::WriteOnly);
        s &amp;lt;&amp;lt; qChecksum(ba.constData(), ba.length());
    &amp;#125; else if (m_protectionMode  ProtectionHash) {<br /> flags |= CryptoFlagHash;<br /> QCryptographicHash hash(QCryptographicHash::Sha1);<br /> hash.addData(ba);
<br /> integrityProtection''= hash.result();<br /> }
<br /> //prepend a random char to the string<br /> char randomChar = char(qrand() &amp; 0xFF);<br /> ba = randomChar + integrityProtection + ba;
<br /> int pos(0);<br /> char lastChar(0);
<br /> int cnt = ba.count();
<br /> while (pos &lt; cnt) {<br /> ba[pos] = ba.at(pos) ^ m_keyParts.at(pos % 8) ^ lastChar;<br /> lastChar = ba.at(pos);<br /> +''pos;<br /> }
<br /> QByteArray resultArray;<br /> resultArray.append(char(0x03)); //version for future updates to algorithm<br /> resultArray.append(char(flags)); //encryption flags<br /> resultArray.append(ba);
<br /> m_lastError = ErrorNoError;<br /> return resultArray;<br />}
<br />QString SimpleCrypt::encryptToString(const QString&amp;amp; plaintext)<br />{<br /> QByteArray plaintextArray = plaintext.toUtf8();<br /> QByteArray cypher = encryptToByteArray(plaintextArray);<br /> QString cypherString = QString::fromAscii(cypher.toBase64());<br /> return cypherString;<br />}
<br />QString SimpleCrypt::encryptToString(QByteArray plaintext)<br />{<br /> QByteArray cypher = encryptToByteArray(plaintext);<br /> QString cypherString = QString::fromAscii(cypher.toBase64());<br /> return cypherString;<br />}
<br />QString SimpleCrypt::decryptToString(const QString &amp;cyphertext)<br />{<br /> QByteArray cyphertextArray = QByteArray::fromBase64(cyphertext.toAscii());<br /> QByteArray plaintextArray = decryptToByteArray(cyphertextArray);<br /> QString plaintext = QString::fromUtf8(plaintextArray, plaintextArray.size());
<br /> return plaintext;<br />}
<br />QString SimpleCrypt::decryptToString(QByteArray cypher)<br />{<br /> QByteArray ba = decryptToByteArray(cypher);<br /> QString plaintext = QString::fromUtf8(ba, ba.size());
<br /> return plaintext;<br />}
<br />QByteArray SimpleCrypt::decryptToByteArray(const QString&amp;amp; cyphertext)<br />{<br /> QByteArray cyphertextArray = QByteArray::fromBase64(cyphertext.toAscii());<br /> QByteArray ba = decryptToByteArray(cyphertextArray);
<br /> return ba;<br />}
<br />QByteArray SimpleCrypt::decryptToByteArray(QByteArray cypher)<br />{<br /> if (m_keyParts.isEmpty()) {<br /> qWarning() &lt;&lt; &quot;No key set.&quot;;<br /> m_lastError = ErrorNoKeySet;<br /> return QByteArray();<br /> }
<br /> QByteArray ba = cypher;
<br /> if( cypher.count() &lt; 3 )<br /> return QByteArray();
<br /> char version = ba.at(0);
<br /> if (version !=3) { //we only work with version 3<br /> m_lastError = ErrorUnknownVersion;<br /> qWarning() &lt;&lt; &quot;Invalid version or not a cyphertext.&quot;;<br /> return QByteArray();<br /> }
<br /> CryptoFlags flags = CryptoFlags(ba.at(1));
<br /> ba = ba.mid(2);<br /> int pos(0);<br /> int cnt(ba.count());<br /> char lastChar = 0;
<br /> while (pos &lt; cnt) {<br /> char currentChar = ba[pos];<br /> ba[pos] = ba.at(pos) ^ lastChar ^ m_keyParts.at(pos % 8);<br /> lastChar = currentChar;<br />''+pos;<br /> }
<br /> ba = ba.mid(1); //chop off the random number at the start
<br /> bool integrityOk(true);<br /> if (flags.testFlag(CryptoFlagChecksum)) {<br /> if (ba.length() &lt; 2) {<br /> m_lastError = ErrorIntegrityFailed;<br /> return QByteArray();<br /> }<br /> quint16 storedChecksum;<br /> {<br /> QDataStream s(&amp;ba, QIODevice::ReadOnly);<br /> s &gt;&gt; storedChecksum;<br /> }<br /> ba = ba.mid(2);<br /> quint16 checksum = qChecksum(ba.constData(), ba.length());<br /> integrityOk = (checksum  storedChecksum);
    &amp;#125; else if (flags.testFlag(CryptoFlagHash)) &amp;#123;
        if (ba.length() &amp;lt; 20) &amp;#123;
            m_lastError = ErrorIntegrityFailed;
            return QByteArray();
        &amp;#125;
        QByteArray storedHash = ba.left(20);
        ba = ba.mid(20);
        QCryptographicHash hash(QCryptographicHash::Sha1);
        hash.addData(ba);
        integrityOk = (hash.result()  storedHash);<br /> }
<br /> if (!integrityOk) {<br /> m_lastError = ErrorIntegrityFailed;<br /> return QByteArray();<br /> }
<br /> if (flags.testFlag(CryptoFlagCompression))<br /> ba = qUncompress(ba);
<br /> m_lastError = ErrorNoError;<br /> return ba;<br />}
<br /></code>
<br />You can copy/paste the code above into your own simplecrypt.h and simplecrypt.cpp files to use it.
<br />h2. Details on the algorithm
<br />The algorithm and data format used in this class, have been detailed on a [[ SimpleCrypt_algorithm_details | separate page]]. On that page, you can find byte-for-byte descriptions of how the cypher text is constructed from the plain text.
<br />h2. Future extensions
<br />I, or somebody else, may choose to extend &lt;code&amp;gt;SimpleCrypt&amp;lt;/code&amp;gt; in the future, or fix a weakness of some kind. To make that possible without loosing the option to read your older encrypted data, the generated cyphertext contains a version number. The idea is that future versions of this code will have a higher version number, but will keep supporting the decryption of cyphertexts with a lower version number. The current version number is 2. Note that these version numbers need not coincide with code version numbers, as a change in the code does not always result in a change in the actual encryption.
<br />h2. Versions
<br />The current code is version 3 of the code.
<br />h4. Version 3
<br />''' Fixed embarrassing mistake with only using 4 out of 8 of the key bytes. Thanks to Gerolf for noticing!
==== Version 2 ====
* Renamed flags to avoid clashes
* Upped version number to 2, but did not retain backwards comparability
* Added optional data integrity protection using either a checksum or a cryptographic hash
* Added error reporting (making is necessary to make the encryption and decryption functions non-const)
==== Version 1 ====
This marks the first public release.
== Feedback ==

Revision as of 08:23, 24 February 2015


[toc align_right="yes&quot; depth="2&quot;]

Simple encryption with SimpleCrypt

Sometimes, you have to store some information that you may want to protect against casual observation. Think about passwords for remote services, for instance. Strong cryptography is obviously the best solution, but it can be hard to use those in the right way, they tend to pull in more libraries, and frankly, it may just be overkill for the situation.

A word of warning

The class presented in this article does not provide strong encryption!

It will protect your data from casual observers, but it will not stand up to dedicated hackers trying to break your secrets. I am not a cryptography expert. Use the code here at your own risk. I am not to be held responsible for any damages that may, directly or indirectly, happen because of your use of this code. Don't say you were not warned.

Introducing SimpleCrypt

The idea of <code&gt;SimpleCrypt&lt;/code&gt; is to provide some basic cryptographic capabilities for simple encryption. Only symmetric encryption is supported (that is: only with the same key for encryption and decryption), and there is no API for streaming data in and out like you often see with more advanced cyphers. If you need stronger cryptography, streaming cyphers or asymmetric keys, take a look at "QCA&quot;:http://delta.affinix.com/qca/ instead.

The <code&gt;SimpleCrypt&lt;/code&gt; class takes a 64 bits key in the form of a quint64. If you use a fixed key build into your program, you can do something like this to initialize your <code&gt;SimpleCrypt&lt;/code&gt; object:

<br />SimpleCrypt crypto(Q_UINT64_C(0x0c2ad4a4acb9f023)); //some random number<br />…<br />


You can also use the <code&gt;setKey()</code&gt; method to set a key on the class.

Selecting a suitable key

To get such random numbers, you might use "this service&quot;:http://www.random.org/integers/?num=10&amp;min=0&amp;max=65535&amp;col=5&amp;base=16&amp;format=html&amp;rnd=new and pick four of the 2 byte hexadecimals that you concatenate together as done above. That works better than trying to make up something semi-random yourself. Of course, you can also use other means to get to a quint64 key, such as using some hash of a password and reducing that to 64 bits.

SimpleCrypt in use

Once setup, you can use <code&gt;SimpleCrypt&lt;/code&gt; to actually encrypt or decrypt data. For the encrypt functions, both the plaintext that you input as the cyphertext that is being outputted can be either a <code&gt;QString&lt;/code&gt; or a <code&gt;QByteArray&lt;/code&gt;. The reverse applies to the decrypt functions. That results in four encrypt methods, and four corresponding decrypt methods:

Encryption methods
  • <code&gt;QString encryptToString(const QString&amp; plaintext)</code&gt;
  • <code&gt;QString encryptToString(QByteArray plaintext)</code&gt;
  • <code&gt;QByteArray encryptToByteArray(const QString&amp; plaintext)</code&gt;
  • <code&gt;QByteArray encryptToByteArray(QByteArray plaintext)</code&gt;
Decryption methods
  • <code&gt;QString decryptToString(const QString&amp; plaintext)</code&gt;
  • <code&gt;QString decryptToString(QByteArray plaintext)</code&gt;
  • <code&gt;QByteArray decryptToByteArray(const QString&amp; plaintext)</code&gt;
  • <code&gt;QByteArray decryptToByteArray(QByteArray plaintext)</code&gt;

Use with QStrings

<br /> SimpleCrypt crypto(Q_UINT64_C(0x0c2ad4a4acb9f023)); //some random number<br /> QString testString(&quot;Lorem ipsum dolor sit amet, consectetur adipiscing elit.&quot;);<br /> QString result = crypto.encryptToString(testString);<br /> QString decrypted = crypto.decryptToString(result);<br /> qDebug() &lt;&lt; testString &lt;&lt; endl &lt;&lt; result &lt;&lt; endl &lt;&lt; decrypted;<br />

The code above encrypts a <code&gt;QString&lt;/code&gt; to a <code&gt;QString&lt;/code&gt;, and then decrypts that string again to a new <code&gt;QString&lt;/code&gt;.

Use with binary data

If you want to encrypt your own binary data, you might do something like this:

<br /> //setup our objects<br /> SimpleCrypt crypto(Q_UINT64_C(0x0c2ad4a4acb9f023)); //some random number<br /> crypto.setCompressionMode(SimpleCrypt::CompressionAlways); //always compress the data, see section below<br /> crypto.setIntegrityProtectionMode(SimpleCrypt::ProtectionHash); //properly protect the integrity of the data<br /> QBuffer buffer;<br /> buffer.open(QIODevice::WriteOnly);<br /> QDataStream s(&amp;buffer);<br /> //stream the data into our buffer<br /> s.setVersion(QDataStream::Qt_4_7);<br /> s &lt;&lt; myString; //stream in a string<br /> s &lt;&lt; myUint16; //stream in an unsigned integer<br /> s &lt;&lt; myImage; //stream in an image<br /> s &lt;&lt; someMoreData;<br /> // … etc.

QByteArray myCypherText = crypto.encryptToByteArray(buffer.data());<br /> if (crypto.lastError() == SimpleCrypt::ErrorNoError) {<br /> // do something relevant with the cyphertext, such as storing it or sending it over a socket to another machine.<br /> }<br /> buffer.close();<br />

Note the use of the data protection feature. I would recommend that you use at least the <code&gt;ProtectionChecksum&lt;/code&gt; level of protection (enabled by default) if you work with binary data, as streaming invalid binary data into your program can lead to big problems.

On the other end, you can now do:

<br /> SimpleCrypt crypto(Q_UINT64_C(0x0c2ad4a4acb9f023)); //same random number: key should match encryption key<br /> QByteArray plaintext = crypto.decryptToByteArray(myCypherText);<br /> if (!crypto.lastError() == SimpleCrypt::ErrorNoError) {<br /> // check why we have an error, use the error code from crypto.lastError() for that<br /> return;<br /> }

QBuffer buffer(&amp;plaintext);<br /> buffer.open(QIODevice::ReadOnly);<br /> QDataStream s(&amp;buffer);<br /> s.setVersion(QDataStream::Qt_4_7);<br /> s &gt;&gt; myString; //stream in a string<br /> s &gt;&gt; myUint16; //stream in an unsigned integer<br /> s &gt;&gt; myImage; //stream in an image<br /> s &gt;&gt; someMoreData;<br /> //etc.

buffer.close();<br />

The code above might crash if the integrity of the data is not guaranteed, for instance by the use of a wrong password. Using the highest level of protection is probably OK here, as we have quite a big blob of data already, so adding the overhead of adding a 20 byte SHA1 cryptographic hash is justifiable.

Compression

For long strings, it can be beneficial to use compression before encryption. Not only does the length of the string decrease, the input will be a bit more random-looking too, resulting in a harder to break cyphertext (at least, in principle, see the warning at the top of this page.) However, for short strings, applying compression can lead to an increase in the string length.

<code&gt;SimpleCrypt&lt;/code&gt; supports three modes for compression before encryption. You can force to always use compression, to never use compression, or to automatically choose the shortest version (either the compressed one or the uncompressed one). The last option is the default option. Note that setting this only affects encryption. For decryption, <code&gt;SimpleCrypt&lt;/code&gt; automatically decompresses the data if compression was used for the encryption.

The code

simplecrypt.h

<br />/*<br />Copyright © 2011, Andre Somers<br />All rights reserved.

Redistribution and use in source and binary forms, with or without<br />modification, are permitted provided that the following conditions are met:<br /> * Redistributions of source code must retain the above copyright<br /> notice, this list of conditions and the following disclaimer.<br /> * Redistributions in binary form must reproduce the above copyright<br /> notice, this list of conditions and the following disclaimer in the<br /> documentation and/or other materials provided with the distribution.<br /> * Neither the name of the Rathenau Instituut, Andre Somers nor the<br /> names of its contributors may be used to endorse or promote products<br /> derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS &quot;AS IS&amp;quot; AND<br />ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED<br />WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE<br />DISCLAIMED. IN NO EVENT SHALL ANDRE SOMERS BE LIABLE FOR ANY<br />DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES<br />(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;<br />LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND<br />ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT<br />(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS<br />SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.<br />'''/
<br />#ifndef SIMPLECRYPT_H<br />#define SIMPLECRYPT_H<br />#include &lt;QString&amp;gt;<br />#include &lt;QVector&amp;gt;<br />#include &lt;QFlags&amp;gt;
<br />/'''*<br />

short Simple encryption and decryption of strings and byte arrays

This class provides a simple implementation of encryption and decryption
of strings and byte arrays.

warning The encryption provided by this class is NOT strong encryption. It may<br /> help to shield things from curious eyes, but it will NOT stand up to someone<br /> determined to break the encryption. Don't say you were not warned.

The class uses a 64 bit key. Simply create an instance of the class, set the key,<br /> and use the encryptToString() method to calculate an encrypted version of the input string.<br /> To decrypt that string again, use an instance of SimpleCrypt initialized with<br /> the same key, and call the decryptToString() method with the encrypted string. If the key<br /> matches, the decrypted version of the string will be returned again.

If you do not provide a key, or if something else is wrong, the encryption and<br /> decryption function will return an empty string or will return a string containing nonsense.<br /> lastError() will return a value indicating if the method was succesful, and if not, why not.

SimpleCrypt is prepared for the case that the encryption and decryption<br /> algorithm is changed in a later version, by prepending a version identifier to the cypertext.<br /> '''/<br />class SimpleCrypt<br />{<br />public:<br /> /'''*<br /> CompressionMode describes if compression will be applied to the data to be<br /> encrypted.<br /> '''/<br /> enum CompressionMode {<br /> CompressionAuto, /'''[[Image:&lt; Only apply compression if that results in a shorter plaintext. */
        CompressionAlways,  /*|]]&lt; Always apply compression. Note that for short inputs, a compression may result in longer data '''/<br /> CompressionNever /'''!&lt; Never apply compression. '''/<br /> };<br /> /'''*<br /> IntegrityProtectionMode describes measures taken to make it possible to detect problems with the data<br /> or wrong decryption keys.

Measures involve adding a checksum or a cryptograhpic hash to the data to be encrypted. This<br /> increases the length of the resulting cypertext, but makes it possible to check if the plaintext<br /> appears to be valid after decryption.<br /> '''/<br /> enum IntegrityProtectionMode {<br /> ProtectionNone, /'''[[Image:&lt; The integerity of the encrypted data is not protected. It is not really possible to detect a wrong key, for instance. */
        ProtectionChecksum,/*|]]&lt; A simple checksum is used to verify that the data is in order. If not, an empty string is returned. '''/<br /> ProtectionHash /'''[[Image:&lt; A cryptographic hash is used to verify the integrity of the data. This method produces a much stronger, but longer check */
    &#125;;
    /**
      Error describes the type of error that occured.
      */
    enum Error &#123;
        ErrorNoError,         /*|]]&lt; No error occurred. '''/<br /> ErrorNoKeySet, /'''[[Image:&lt; No key was set. You can not encrypt or decrypt without a valid key. */
        ErrorUnknownVersion,  /*|]]&lt; The version of this data is unknown, or the data is otherwise not valid. '''/<br /> ErrorIntegrityFailed, /'''!&lt; The integrity check of the data failed. Perhaps the wrong key was used. '''/<br /> };
<br /> /'''*<br /> Constructor.

Constructs a SimpleCrypt instance without a valid key set on it.<br /> '''/<br /> SimpleCrypt();<br /> /'''*<br /> Constructor.

Constructs a SimpleCrypt instance and initializes it with the given

arg key.
/
explicit SimpleCrypt(quint64 key);

/*
(Re-) initializes the key with the given

arg key.<br /> '''/<br /> void setKey(quint64 key);<br /> /'''*<br /> Returns true if SimpleCrypt has been initialized with a key.<br /> '''/<br /> bool hasKey() const {return !m_keyParts.isEmpty();}
<br /> /'''*<br /> Sets the compression mode to use when encrypting data. The default mode is Auto.

Note that decryption is not influenced by this mode, as the decryption recognizes<br /> what mode was used when encrypting.<br /> '''/<br /> void setCompressionMode(CompressionMode mode) {m_compressionMode = mode;}<br /> /'''*<br /> Returns the CompressionMode that is currently in use.<br /> '''/<br /> CompressionMode compressionMode() const {return m_compressionMode;}
<br /> /'''*<br /> Sets the integrity mode to use when encrypting data. The default mode is Checksum.

Note that decryption is not influenced by this mode, as the decryption recognizes<br /> what mode was used when encrypting.<br /> '''/<br /> void setIntegrityProtectionMode(IntegrityProtectionMode mode) {m_protectionMode = mode;}<br /> /'''*<br /> Returns the IntegrityProtectionMode that is currently in use.<br /> '''/<br /> IntegrityProtectionMode integrityProtectionMode() const {return m_protectionMode;}
<br /> /'''*<br /> Returns the last error that occurred.<br /> '''/<br /> Error lastError() const {return m_lastError;}
<br /> /'''*<br /> Encrypts the

arg plaintext string with the key the class was initialized with, and returns
a cyphertext the result. The result is a base64 encoded version of the binary array that is the
actual result of the string, so it can be stored easily in a text format.
/
QString encryptToString(const QString&amp; plaintext) ;
/*
Encrypts the

arg plaintext QByteArray with the key the class was initialized with, and returns<br /> a cyphertext the result. The result is a base64 encoded version of the binary array that is the<br /> actual result of the encryption, so it can be stored easily in a text format.<br /> '''/<br /> QString encryptToString(QByteArray plaintext) ;<br /> /'''*<br /> Encrypts the

arg plaintext string with the key the class was initialized with, and returns
a binary cyphertext in a QByteArray the result.
This method returns a byte array, that is useable for storing a binary format. If you need
a string you can store in a text file, use encryptToString() instead.
/
QByteArray encryptToByteArray(const QString&amp; plaintext) ;
/
*
Encrypts the

arg plaintext QByteArray with the key the class was initialized with, and returns<br /> a binary cyphertext in a QByteArray the result.

This method returns a byte array, that is useable for storing a binary format. If you need<br /> a string you can store in a text file, use encryptToString() instead.<br /> '''/<br /> QByteArray encryptToByteArray(QByteArray plaintext) ;
<br /> /'''*<br /> Decrypts a cyphertext string encrypted with this class with the set key back to the<br /> plain text version.

If an error occured, such as non-matching keys between encryption and decryption,<br /> an empty string or a string containing nonsense may be returned.<br /> '''/<br /> QString decryptToString(const QString&amp;amp; cyphertext) ;<br /> /'''*<br /> Decrypts a cyphertext string encrypted with this class with the set key back to the<br /> plain text version.

If an error occured, such as non-matching keys between encryption and decryption,<br /> an empty string or a string containing nonsense may be returned.<br /> '''/<br /> QByteArray decryptToByteArray(const QString&amp;amp; cyphertext) ;<br /> /'''*<br /> Decrypts a cyphertext binary encrypted with this class with the set key back to the<br /> plain text version.

If an error occured, such as non-matching keys between encryption and decryption,<br /> an empty string or a string containing nonsense may be returned.<br /> '''/<br /> QString decryptToString(QByteArray cypher) ;<br /> /'''*<br /> Decrypts a cyphertext binary encrypted with this class with the set key back to the<br /> plain text version.

If an error occured, such as non-matching keys between encryption and decryption,<br /> an empty string or a string containing nonsense may be returned.<br /> '''/<br /> QByteArray decryptToByteArray(QByteArray cypher) ;
<br /> //enum to describe options that have been used for the encryption. Currently only one, but<br /> //that only leaves room for future extensions like adding a cryptographic hash…<br /> enum CryptoFlag{CryptoFlagNone = 0,<br /> CryptoFlagCompression = 0x01,<br /> CryptoFlagChecksum = 0x02,<br /> CryptoFlagHash = 0x04<br /> };<br /> Q_DECLARE_FLAGS(CryptoFlags, CryptoFlag);<br />private:
<br /> void splitKey();
<br /> quint64 m_key;<br /> QVector&amp;lt;char&amp;gt; m_keyParts;<br /> CompressionMode m_compressionMode;<br /> IntegrityProtectionMode m_protectionMode;<br /> Error m_lastError;<br />};<br />Q_DECLARE_OPERATORS_FOR_FLAGS(SimpleCrypt::CryptoFlags)
<br />#endif // SimpleCrypt_H
<br />


simplecrypt.cpp

<br />/'''<br />Copyright © 2011, Andre Somers<br />All rights reserved.

Redistribution and use in source and binary forms, with or without<br />modification, are permitted provided that the following conditions are met:<br /> * Redistributions of source code must retain the above copyright<br /> notice, this list of conditions and the following disclaimer.<br /> * Redistributions in binary form must reproduce the above copyright<br /> notice, this list of conditions and the following disclaimer in the<br /> documentation and/or other materials provided with the distribution.<br /> * Neither the name of the Rathenau Instituut, Andre Somers nor the<br /> names of its contributors may be used to endorse or promote products<br /> derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS &quot;AS IS&amp;quot; AND<br />ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED<br />WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE<br />DISCLAIMED. IN NO EVENT SHALL ANDRE SOMERS BE LIABLE FOR ANY<br />DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES<br />(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;<br />LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND<br />ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT<br />(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS<br />SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.<br />'''/<br />#include &quot;simplecrypt.h&amp;quot;<br />#include &lt;QByteArray&amp;gt;<br />#include &lt;QtDebug&amp;gt;<br />#include &lt;QtGlobal&amp;gt;<br />#include &lt;QDateTime&amp;gt;<br />#include &lt;QCryptographicHash&amp;gt;
<br />SimpleCrypt::SimpleCrypt():<br /> m_key(0),<br /> m_compressionMode(CompressionAuto),<br /> m_protectionMode(ProtectionChecksum),<br /> m_lastError(ErrorNoError)<br />{<br /> qsrand(uint(QDateTime::currentMSecsSinceEpoch() &amp; 0xFFFF));<br />}
<br />SimpleCrypt::SimpleCrypt(quint64 key):<br /> m_key(key),<br /> m_compressionMode(CompressionAuto),<br /> m_protectionMode(ProtectionChecksum),<br /> m_lastError(ErrorNoError)<br />{<br /> qsrand(uint(QDateTime::currentMSecsSinceEpoch() &amp; 0xFFFF));<br /> splitKey();<br />}
<br />void SimpleCrypt::setKey(quint64 key)<br />{<br /> m_key = key;<br /> splitKey();<br />}
<br />void SimpleCrypt::splitKey()<br />{<br /> m_keyParts.clear();<br /> m_keyParts.resize(8);<br /> for (int i=0;i&amp;lt;8;i+'') {<br /> quint64 part = m_key;<br /> for (int j=i; j&amp;gt;0; j)<br /> part = part &gt;&gt; 8;<br /> part = part &amp; 0xff;<br /> m_keyParts[i] = static_cast&amp;lt;char&amp;gt;(part);<br /> }<br />}
<br />QByteArray SimpleCrypt::encryptToByteArray(const QString&amp;amp; plaintext)<br />{<br /> QByteArray plaintextArray = plaintext.toUtf8();<br /> return encryptToByteArray(plaintextArray);<br />}
<br />QByteArray SimpleCrypt::encryptToByteArray(QByteArray plaintext)<br />{<br /> if (m_keyParts.isEmpty()) {<br /> qWarning() &lt;&lt; &quot;No key set.&quot;;<br /> m_lastError = ErrorNoKeySet;<br /> return QByteArray();<br /> }

<br /> QByteArray ba = plaintext;
<br /> CryptoFlags flags = CryptoFlagNone;<br /> if (m_compressionMode  CompressionAlways) &amp;#123;
        ba = qCompress(ba, 9); //maximum compression
        flags |= CryptoFlagCompression;
    &amp;#125; else if (m_compressionMode  CompressionAuto) {<br /> QByteArray compressed = qCompress(ba, 9);<br /> if (compressed.count() &lt; ba.count()) {<br /> ba = compressed;<br /> flags |= CryptoFlagCompression;<br /> }<br /> }
<br /> QByteArray integrityProtection;<br /> if (m_protectionMode  ProtectionChecksum) &amp;#123;
        flags |= CryptoFlagChecksum;
        QDataStream s(&amp;amp;integrityProtection, QIODevice::WriteOnly);
        s &amp;lt;&amp;lt; qChecksum(ba.constData(), ba.length());
    &amp;#125; else if (m_protectionMode  ProtectionHash) {<br /> flags |= CryptoFlagHash;<br /> QCryptographicHash hash(QCryptographicHash::Sha1);<br /> hash.addData(ba);
<br /> integrityProtection''= hash.result();<br /> }
<br /> //prepend a random char to the string<br /> char randomChar = char(qrand() &amp; 0xFF);<br /> ba = randomChar + integrityProtection + ba;
<br /> int pos(0);<br /> char lastChar(0);
<br /> int cnt = ba.count();
<br /> while (pos &lt; cnt) {<br /> ba[pos] = ba.at(pos) ^ m_keyParts.at(pos % 8) ^ lastChar;<br /> lastChar = ba.at(pos);<br /> +''pos;<br /> }
<br /> QByteArray resultArray;<br /> resultArray.append(char(0x03)); //version for future updates to algorithm<br /> resultArray.append(char(flags)); //encryption flags<br /> resultArray.append(ba);
<br /> m_lastError = ErrorNoError;<br /> return resultArray;<br />}
<br />QString SimpleCrypt::encryptToString(const QString&amp;amp; plaintext)<br />{<br /> QByteArray plaintextArray = plaintext.toUtf8();<br /> QByteArray cypher = encryptToByteArray(plaintextArray);<br /> QString cypherString = QString::fromAscii(cypher.toBase64());<br /> return cypherString;<br />}
<br />QString SimpleCrypt::encryptToString(QByteArray plaintext)<br />{<br /> QByteArray cypher = encryptToByteArray(plaintext);<br /> QString cypherString = QString::fromAscii(cypher.toBase64());<br /> return cypherString;<br />}
<br />QString SimpleCrypt::decryptToString(const QString &amp;cyphertext)<br />{<br /> QByteArray cyphertextArray = QByteArray::fromBase64(cyphertext.toAscii());<br /> QByteArray plaintextArray = decryptToByteArray(cyphertextArray);<br /> QString plaintext = QString::fromUtf8(plaintextArray, plaintextArray.size());
<br /> return plaintext;<br />}
<br />QString SimpleCrypt::decryptToString(QByteArray cypher)<br />{<br /> QByteArray ba = decryptToByteArray(cypher);<br /> QString plaintext = QString::fromUtf8(ba, ba.size());
<br /> return plaintext;<br />}
<br />QByteArray SimpleCrypt::decryptToByteArray(const QString&amp;amp; cyphertext)<br />{<br /> QByteArray cyphertextArray = QByteArray::fromBase64(cyphertext.toAscii());<br /> QByteArray ba = decryptToByteArray(cyphertextArray);
<br /> return ba;<br />}
<br />QByteArray SimpleCrypt::decryptToByteArray(QByteArray cypher)<br />{<br /> if (m_keyParts.isEmpty()) {<br /> qWarning() &lt;&lt; &quot;No key set.&quot;;<br /> m_lastError = ErrorNoKeySet;<br /> return QByteArray();<br /> }
<br /> QByteArray ba = cypher;
<br /> if( cypher.count() &lt; 3 )<br /> return QByteArray();
<br /> char version = ba.at(0);
<br /> if (version !=3) { //we only work with version 3<br /> m_lastError = ErrorUnknownVersion;<br /> qWarning() &lt;&lt; &quot;Invalid version or not a cyphertext.&quot;;<br /> return QByteArray();<br /> }
<br /> CryptoFlags flags = CryptoFlags(ba.at(1));
<br /> ba = ba.mid(2);<br /> int pos(0);<br /> int cnt(ba.count());<br /> char lastChar = 0;
<br /> while (pos &lt; cnt) {<br /> char currentChar = ba[pos];<br /> ba[pos] = ba.at(pos) ^ lastChar ^ m_keyParts.at(pos % 8);<br /> lastChar = currentChar;<br />''+pos;<br /> }
<br /> ba = ba.mid(1); //chop off the random number at the start
<br /> bool integrityOk(true);<br /> if (flags.testFlag(CryptoFlagChecksum)) {<br /> if (ba.length() &lt; 2) {<br /> m_lastError = ErrorIntegrityFailed;<br /> return QByteArray();<br /> }<br /> quint16 storedChecksum;<br /> {<br /> QDataStream s(&amp;ba, QIODevice::ReadOnly);<br /> s &gt;&gt; storedChecksum;<br /> }<br /> ba = ba.mid(2);<br /> quint16 checksum = qChecksum(ba.constData(), ba.length());<br /> integrityOk = (checksum  storedChecksum);
    &amp;#125; else if (flags.testFlag(CryptoFlagHash)) &amp;#123;
        if (ba.length() &amp;lt; 20) &amp;#123;
            m_lastError = ErrorIntegrityFailed;
            return QByteArray();
        &amp;#125;
        QByteArray storedHash = ba.left(20);
        ba = ba.mid(20);
        QCryptographicHash hash(QCryptographicHash::Sha1);
        hash.addData(ba);
        integrityOk = (hash.result()  storedHash);<br /> }
<br /> if (!integrityOk) {<br /> m_lastError = ErrorIntegrityFailed;<br /> return QByteArray();<br /> }
<br /> if (flags.testFlag(CryptoFlagCompression))<br /> ba = qUncompress(ba);
<br /> m_lastError = ErrorNoError;<br /> return ba;<br />}
<br />


You can copy/paste the code above into your own simplecrypt.h and simplecrypt.cpp files to use it.
h2. Details on the algorithm
The algorithm and data format used in this class, have been detailed on a separate page. On that page, you can find byte-for-byte descriptions of how the cypher text is constructed from the plain text.


h2. Future extensions
I, or somebody else, may choose to extend <code&gt;SimpleCrypt&lt;/code&gt; in the future, or fix a weakness of some kind. To make that possible without loosing the option to read your older encrypted data, the generated cyphertext contains a version number. The idea is that future versions of this code will have a higher version number, but will keep supporting the decryption of cyphertexts with a lower version number. The current version number is 2. Note that these version numbers need not coincide with code version numbers, as a change in the code does not always result in a change in the actual encryption.
h2. Versions
The current code is version 3 of the code.
h4. Version 3
Fixed embarrassing mistake with only using 4 out of 8 of the key bytes. Thanks to Gerolf for noticing!

Version 2

  • Renamed flags to avoid clashes
  • Upped version number to 2, but did not retain backwards comparability
  • Added optional data integrity protection using either a checksum or a cryptographic hash
  • Added error reporting (making is necessary to make the encryption and decryption functions non-const)

Version 1

This marks the first public release.

Feedback