QtLingo 1
QtLingo is an Application to make Qt Computer Translations easier
SimpleCrypt Class Reference

Simple encryption and decryption of strings and byte arrays. More...

#include <SimpleCrypt.h>

Public Types

enum  CompressionMode { CompressionAuto , CompressionAlways , CompressionNever }
 
enum  IntegrityProtectionMode { ProtectionNone , ProtectionChecksum , ProtectionHash }
 
enum  Error { ErrorNoError , ErrorNoKeySet , ErrorUnknownVersion , ErrorIntegrityFailed }
 
enum  CryptoFlag { CryptoFlagNone = 0 , CryptoFlagCompression = 0x01 , CryptoFlagChecksum = 0x02 , CryptoFlagHash = 0x04 }
 

Public Member Functions

 SimpleCrypt ()
 Constructor. SimpleCrypt. More...
 
 SimpleCrypt (quint64 key)
 Constructor. SimpleCrypt. More...
 
void setKey (quint64 key)
 set Key. setKey More...
 
bool hasKey () const
 
void setCompressionMode (CompressionMode mode)
 
CompressionMode compressionMode () const
 
void setIntegrityProtectionMode (IntegrityProtectionMode mode)
 
IntegrityProtectionMode integrityProtectionMode () const
 
Error lastError () const
 
QString encryptToString (const QString &plaintext)
 encrypt To String QString. encryptToString More...
 
QString encryptToString (const QByteArray &plaintext)
 encrypt To String QByteArray. encryptToString More...
 
QByteArray encryptToByteArray (const QString &plaintext)
 encrypt To Byte Array QString. encryptToByteArray More...
 
QByteArray encryptToByteArray (const QByteArray &plaintext)
 encrypt To Byte Array QByteArray. encryptToByteArray More...
 
QString decryptToString (const QString &cyphertext)
 decrypt To String QString. decryptToString More...
 
QByteArray decryptToByteArray (const QString &cyphertext)
 decrypt To Byte Array QString. decryptToByteArray More...
 
QString decryptToString (const QByteArray &cypher)
 decrypt To String QByteArray. decryptToString More...
 
QByteArray decryptToByteArray (QByteArray cypher)
 decrypt To Byte Array QByteArray. decryptToByteArray More...
 
 Q_DECLARE_FLAGS (CryptoFlags, CryptoFlag)
 
void setDebugMessage (bool thisState)
 set Debug Message More...
 
bool getDebugMessage ()
 get Debug Message More...
 
void setMessage (const QString &thisMessage)
 set Message More...
 

Detailed Description

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 help to shield things from curious eyes, but it will NOT stand up to someone determined to break the encryption. Do not say you were not warned.

The class uses a 64 bit key. Simply create an instance of the class, set the key, and use the encryptToString() method to calculate an encrypted version of the input string. To decrypt that string again, use an instance of SimpleCrypt initialized with the same key, and call the decryptToString() method with the encrypted string. If the key 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 decryption function will return an empty string or will return a string containing nonsense. 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 algorithm is changed in a later version, by prepending a version identifier to the cypertext.

Definition at line 71 of file SimpleCrypt.h.

Member Enumeration Documentation

◆ CompressionMode

CompressionMode describes if compression will be applied to the data to be encrypted.

Enumerator
CompressionAuto 

Only apply compression if that results in a shorter plaintext.

CompressionAlways 

Always apply compression. Note that for short inputs, a compression may result in longer data

CompressionNever 

Never apply compression.

Definition at line 77 of file SimpleCrypt.h.

◆ CryptoFlag

enum to describe options that have been used for the encryption. Currently only one, but that only leaves room for future extensions like adding a cryptographic hash...

Enumerator
CryptoFlagNone 

CryptoFlagNone

Crypto Flag None

CryptoFlagCompression 

CryptoFlagCompression

Crypto Flag Compression

CryptoFlagChecksum 

CryptoFlagChecksum

Crypto Flag Checksum

CryptoFlagHash 

CryptoFlagHash

Crypto Flag Hash

Definition at line 204 of file SimpleCrypt.h.

205 {
206 CryptoFlagNone = 0,
207 CryptoFlagCompression = 0x01,
208 CryptoFlagChecksum = 0x02,
209 CryptoFlagHash = 0x04
210 };
@ CryptoFlagChecksum
CryptoFlagChecksum
Definition: SimpleCrypt.h:208
@ CryptoFlagNone
CryptoFlagNone
Definition: SimpleCrypt.h:206
@ CryptoFlagCompression
CryptoFlagCompression
Definition: SimpleCrypt.h:207
@ CryptoFlagHash
CryptoFlagHash
Definition: SimpleCrypt.h:209

◆ Error

Enumerator
ErrorNoError 

No error occurred.

ErrorNoKeySet 

No key was set. You can not encrypt or decrypt without a valid key.

ErrorUnknownVersion 

The version of this data is unknown, or the data is otherwise not valid.

ErrorIntegrityFailed 

The integrity check of the data failed. Perhaps the wrong key was used.

Definition at line 96 of file SimpleCrypt.h.

◆ IntegrityProtectionMode

IntegrityProtectionMode describes measures taken to make it possible to detect problems with the data, or wrong decryption keys. Measures involve adding a checksum or a cryptograhpic hash to the data to be encrypted. This increases the length of the resulting cypertext, but makes it possible to check if the plaintext appears to be valid after decryption.

Enumerator
ProtectionNone 

The integerity of the encrypted data is not protected. It is not really possible to detect a wrong key, for instance.

ProtectionChecksum 

A simple checksum is used to verify that the data is in order. If not, an empty string is returned.

ProtectionHash 

A cryptographic hash is used to verify the integrity of the data. This method produces a much stronger, but longer check

Definition at line 89 of file SimpleCrypt.h.

Constructor & Destructor Documentation

◆ SimpleCrypt() [1/2]

SimpleCrypt::SimpleCrypt ( )

Constructor. SimpleCrypt.

Constructor. Constructs a SimpleCrypt instance without a valid key set on it.

Definition at line 34 of file SimpleCrypt.cpp.

34 : myKey(0), myCompressionMode(CompressionAuto), myProtectionMode(ProtectionChecksum), myLastError(ErrorNoError)
35{
36 QRandomGenerator generator(uint(QDateTime::currentMSecsSinceEpoch() & 0xFFFF));
37 generator.generate();
38 // qsrand(uint(QDateTime::currentMSecsSinceEpoch() & 0xFFFF));
39}

◆ SimpleCrypt() [2/2]

SimpleCrypt::SimpleCrypt ( quint64  key)
explicit

Constructor. SimpleCrypt.

Constructor. Constructs a SimpleCrypt instance and initializes it with the given

  • key.

Definition at line 44 of file SimpleCrypt.cpp.

44 : myKey(key), myCompressionMode(CompressionAuto), myProtectionMode(ProtectionChecksum), myLastError(ErrorNoError)
45{
46 QRandomGenerator generator(uint(QDateTime::currentMSecsSinceEpoch() & 0xFFFF));
47 generator.generate();
48 // qsrand(uint(QDateTime::currentMSecsSinceEpoch() & 0xFFFF));
49 splitKey();
50}

Member Function Documentation

◆ compressionMode()

CompressionMode SimpleCrypt::compressionMode ( ) const
inline

Returns the CompressionMode that is currently in use.

Definition at line 130 of file SimpleCrypt.h.

130{return myCompressionMode;}

◆ decryptToByteArray() [1/2]

QByteArray SimpleCrypt::decryptToByteArray ( const QString &  cyphertext)

decrypt To Byte Array QString. decryptToByteArray

Decrypts a cyphertext string encrypted with this class with the set key back to the plain text version.

If an error occured, such as non-matching keys between encryption and decryption, an empty string or a string containing nonsense may be returned.

Definition at line 222 of file SimpleCrypt.cpp.

223{
224 QByteArray cyphertextArray = QByteArray::fromBase64(cyphertext.toLatin1());
225 QByteArray ba = decryptToByteArray(cyphertextArray);
226
227 return ba;
228}
QByteArray decryptToByteArray(const QString &cyphertext)
decrypt To Byte Array QString. decryptToByteArray

◆ decryptToByteArray() [2/2]

QByteArray SimpleCrypt::decryptToByteArray ( QByteArray  cypher)

decrypt To Byte Array QByteArray. decryptToByteArray

Decrypts a cyphertext binary encrypted with this class with the set key back to the plain text version.

If an error occured, such as non-matching keys between encryption and decryption, an empty string or a string containing nonsense may be returned.

Definition at line 233 of file SimpleCrypt.cpp.

234{
235 if (myKeyParts.isEmpty())
236 {
237 qWarning() << "No key set.";
238 myLastError = ErrorNoKeySet;
239 return QByteArray();
240 }
241
242 QByteArray ba = cypher;
243
244 if( cypher.count() < 3 )
245 { return QByteArray(); }
246
247 char version = ba.at(0);
248
249 if (version != 3)
250 { // we only work with version 3
251 myLastError = ErrorUnknownVersion;
252 qWarning() << "Invalid version or not a cyphertext.";
253 return QByteArray();
254 }
255
256 CryptoFlags flags = CryptoFlags(ba.at(1));
257
258 ba = ba.mid(2);
259 int pos(0);
260 int cnt(ba.count());
261 char lastChar = 0;
262
263 while (pos < cnt)
264 {
265 char currentChar = ba[pos];
266 ba[pos] = ba.at(pos) ^ lastChar ^ myKeyParts.at(pos % 8);
267 lastChar = currentChar;
268 ++pos;
269 }
270
271 ba = ba.mid(1); // chop off the random number at the start
272
273 bool integrityOk(true);
274 if (flags.testFlag(CryptoFlagChecksum))
275 {
276 if (ba.length() < 2)
277 {
278 myLastError = ErrorIntegrityFailed;
279 return QByteArray();
280 }
281 quint16 storedChecksum;
282 {
283 QDataStream s(&ba, QIODevice::ReadOnly);
284 s >> storedChecksum;
285 }
286 ba = ba.mid(2);
287 quint16 checksum = qChecksum(ba.constData(), ba.length());
288 integrityOk = (checksum == storedChecksum);
289 }
290 else if (flags.testFlag(CryptoFlagHash))
291 {
292 if (ba.length() < 20)
293 {
294 myLastError = ErrorIntegrityFailed;
295 return QByteArray();
296 }
297 QByteArray storedHash = ba.left(20);
298 ba = ba.mid(20);
299 QCryptographicHash hash(QCryptographicHash::Sha1);
300 hash.addData(ba);
301 integrityOk = (hash.result() == storedHash);
302 }
303
304 if (!integrityOk)
305 {
306 myLastError = ErrorIntegrityFailed;
307 return QByteArray();
308 }
309
310 if (flags.testFlag(CryptoFlagCompression))
311 { ba = qUncompress(ba); }
312
313 myLastError = ErrorNoError;
314 return ba;
315}

◆ decryptToString() [1/2]

QString SimpleCrypt::decryptToString ( const QByteArray &  cypher)

decrypt To String QByteArray. decryptToString

Decrypts a cyphertext binary encrypted with this class with the set key back to the plain text version. If an error occured, such as non-matching keys between encryption and decryption, an empty string or a string containing nonsense may be returned.

Definition at line 211 of file SimpleCrypt.cpp.

212{
213 QByteArray ba = decryptToByteArray(cypher);
214 QString plaintext = QString::fromUtf8(ba, ba.size());
215
216 return plaintext;
217}

◆ decryptToString() [2/2]

QString SimpleCrypt::decryptToString ( const QString &  cyphertext)

decrypt To String QString. decryptToString

Decrypts a cyphertext string encrypted with this class with the set key back to the plain text version.

If an error occured, such as non-matching keys between encryption and decryption, an empty string or a string containing nonsense may be returned.

Definition at line 199 of file SimpleCrypt.cpp.

200{
201 QByteArray cyphertextArray = QByteArray::fromBase64(cyphertext.toLatin1());
202 QByteArray plaintextArray = decryptToByteArray(cyphertextArray);
203 QString plaintext = QString::fromUtf8(plaintextArray, plaintextArray.size());
204
205 return plaintext;
206}

◆ encryptToByteArray() [1/2]

QByteArray SimpleCrypt::encryptToByteArray ( const QByteArray &  plaintext)

encrypt To Byte Array QByteArray. encryptToByteArray

Encrypts the

  • plaintext QByteArray 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.

Definition at line 105 of file SimpleCrypt.cpp.

106{
107 if (myKeyParts.isEmpty())
108 {
109 qWarning() << "No key set.";
110 myLastError = ErrorNoKeySet;
111 return QByteArray();
112 }
113
114 QByteArray ba = plaintext;
115
116 CryptoFlags flags = CryptoFlagNone;
117 if (myCompressionMode == CompressionAlways)
118 {
119 ba = qCompress(ba, 9); // maximum compression
120 flags |= CryptoFlagCompression;
121 }
122 else if (myCompressionMode == CompressionAuto)
123 {
124 QByteArray compressed = qCompress(ba, 9);
125 if (compressed.count() < ba.count())
126 {
127 ba = compressed;
128 flags |= CryptoFlagCompression;
129 }
130 }
131
132 QByteArray integrityProtection;
133 if (myProtectionMode == ProtectionChecksum)
134 {
135 flags |= CryptoFlagChecksum;
136 QDataStream s(&integrityProtection, QIODevice::WriteOnly);
137 s << qChecksum(ba.constData(), ba.length());
138 }
139 else if (myProtectionMode == ProtectionHash)
140 {
141 flags |= CryptoFlagHash;
142 QCryptographicHash hash(QCryptographicHash::Sha1);
143 hash.addData(ba);
144
145 integrityProtection += hash.result();
146 }
147 // prepend a random char to the string
148 QRandomGenerator generator(uint(QDateTime::currentMSecsSinceEpoch() & 0xFFFF));
149 char randomChar = char(generator.generate() & 0xFF);
150 // char randomChar = char(qrand() & 0xFF);
151
152 ba = randomChar + integrityProtection + ba;
153
154 int pos(0);
155 char lastChar(0);
156
157 int cnt = ba.count();
158
159 while (pos < cnt)
160 {
161 ba[pos] = ba.at(pos) ^ myKeyParts.at(pos % 8) ^ lastChar;
162 lastChar = ba.at(pos);
163 ++pos;
164 }
165
166 QByteArray resultArray;
167 resultArray.append(char(0x03)); // version for future updates to algorithm
168 resultArray.append(char(flags)); // encryption flags
169 resultArray.append(ba);
170
171 myLastError = ErrorNoError;
172 return resultArray;
173}

◆ encryptToByteArray() [2/2]

QByteArray SimpleCrypt::encryptToByteArray ( const QString &  plaintext)

encrypt To Byte Array QString. encryptToByteArray

Encrypts the

  • 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.

Definition at line 96 of file SimpleCrypt.cpp.

97{
98 QByteArray plaintextArray = plaintext.toUtf8();
99 return encryptToByteArray(plaintextArray);
100}
QByteArray encryptToByteArray(const QString &plaintext)
encrypt To Byte Array QString. encryptToByteArray
Definition: SimpleCrypt.cpp:96

◆ encryptToString() [1/2]

QString SimpleCrypt::encryptToString ( const QByteArray &  plaintext)

encrypt To String QByteArray. encryptToString

Encrypts the

  • plaintext QByteArray 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 encryption, so it can be stored easily in a text format.

Definition at line 189 of file SimpleCrypt.cpp.

190{
191 QByteArray cypher = encryptToByteArray(plaintext);
192 QString cypherString = QString::fromLatin1(cypher.toBase64());
193 return cypherString;
194}

◆ encryptToString() [2/2]

QString SimpleCrypt::encryptToString ( const QString &  plaintext)

encrypt To String QString. encryptToString

Encrypts the

  • 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.

Definition at line 178 of file SimpleCrypt.cpp.

179{
180 QByteArray plaintextArray = plaintext.toUtf8();
181 QByteArray cypher = encryptToByteArray(plaintextArray);
182 QString cypherString = QString::fromLatin1(cypher.toBase64());
183 return cypherString;
184}

◆ getDebugMessage()

bool SimpleCrypt::getDebugMessage ( )

get Debug Message

get Debug Message. getDebugMessage

Definition at line 63 of file SimpleCrypt.cpp.

64{
65 return isDebugMessage;
66}

◆ hasKey()

bool SimpleCrypt::hasKey ( ) const
inline

Returns true if SimpleCrypt has been initialized with a key.

Definition at line 120 of file SimpleCrypt.h.

120{return !myKeyParts.isEmpty();}

◆ integrityProtectionMode()

IntegrityProtectionMode SimpleCrypt::integrityProtectionMode ( ) const
inline

Definition at line 138 of file SimpleCrypt.h.

138{return myProtectionMode;}

◆ lastError()

Error SimpleCrypt::lastError ( ) const
inline

Definition at line 141 of file SimpleCrypt.h.

141{return myLastError;}

◆ Q_DECLARE_FLAGS()

SimpleCrypt::Q_DECLARE_FLAGS ( CryptoFlags  ,
CryptoFlag   
)

◆ setCompressionMode()

void SimpleCrypt::setCompressionMode ( CompressionMode  mode)
inline

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 what mode was used when encrypting.

Definition at line 126 of file SimpleCrypt.h.

126{myCompressionMode = mode;}

◆ setDebugMessage()

void SimpleCrypt::setDebugMessage ( bool  thisState)

set Debug Message

set Debug Message. setDebugMessage

Definition at line 55 of file SimpleCrypt.cpp.

56{
57 isDebugMessage = thisState;
58}

◆ setIntegrityProtectionMode()

void SimpleCrypt::setIntegrityProtectionMode ( IntegrityProtectionMode  mode)
inline

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 what mode was used when encrypting.

Definition at line 136 of file SimpleCrypt.h.

136{myProtectionMode = mode;}

◆ setKey()

void SimpleCrypt::setKey ( quint64  key)

set Key. setKey

(Re-) initializes the key with the given

  • key.

Definition at line 71 of file SimpleCrypt.cpp.

72{
73 myKey = key;
74 splitKey();
75}

◆ setMessage()

void SimpleCrypt::setMessage ( const QString &  thisMessage)

set Message

set Message. setMessage

Definition at line 320 of file SimpleCrypt.cpp.

321{
322 if (isDebugMessage)
323 {
324 qDebug() << thisMessage;
325 //std::cout << thisMessage.toStdString() << std::endl;
326 }
327}

The documentation for this class was generated from the following files: