UltraScan III
us_crypto.cpp
Go to the documentation of this file.
1 
3 #include "us_crypto.h"
4 #include <openssl/evp.h>
5 
6 QStringList US_Crypto::encrypt( const QString& plain_text, const QString& pw )
7 {
8  QStringList result;
9 
10  // Seed the pseudo random number generator if needed
11  static bool seed = false;
12 
13  if ( ! seed )
14  {
15  QTime time = QTime::currentTime();
16  // Not a great amount of entropy, but probably good enough for us
17 
18  qsrand( (uint)time.msec() );
19  seed = true;
20  }
21 
22  // Determine the initialization vector
23  QByteArray iv_ba( 16, '0' );
24 
25  for ( int i = 0; i < 16; i++ )
26  iv_ba[ i ] = qrand() % 256;
27 
28  uchar* iv_ptr = (uchar*)iv_ba.data();
29 
30  uchar key[ 16 ]; // The key is a 16 byte array
31  memset( key, 0, 16 ); // Zero it out
32 
33  for ( int i = 0; i < pw.size(); i++ ) // Copy the password
34  key[ i ] = pw[ i ].cell();
35 
36  QString plaintext = plain_text;
37  QByteArray plain_ba = plaintext.toAscii();
38  uchar* plain_ptr = (uchar*)plain_ba.data();
39 
40  EVP_CIPHER_CTX ctx;
41  uchar out[ 100 ]; // Assume the plaintext is < 99 characters
42  int out_length;
43  int final_length;
44 
45  EVP_EncryptInit ( &ctx, EVP_aes_128_cbc(), key, iv_ptr );
46  EVP_EncryptUpdate( &ctx, out, &out_length, plain_ptr, plaintext.size() );
47  EVP_EncryptFinal ( &ctx, &out[ out_length ], &final_length );
48 
49  int c_size = out_length + final_length;
50 
51  QByteArray cipher_ba = QByteArray( (const char*)out, c_size );
52 
53  result << cipher_ba.toHex() << iv_ba.toHex();
54 
55  return result;
56 }
58 QString US_Crypto::decrypt( const QString& ciphertext, const QString& pw,
59  const QString& initVector )
60 {
61  if ( pw.size() == 0 ) return QString();
62 
63  uchar key[ 16 ]; // The key is a 16 byte array
64  memset( key, 0, 16 ); // Zero it out
65 
66  for ( int i = 0; i < pw.size(); i++ ) // Copy the password
67  key[ i ] = pw[ i ].cell();
68 
69  QByteArray iv_ba = QByteArray::fromHex( initVector.toAscii() );
70  uchar* iv_ptr = (uchar*)iv_ba.data();
71 
72  QByteArray cipher_ba = QByteArray::fromHex( ciphertext.toAscii() );
73  uchar* cipher_ptr = (uchar*)cipher_ba.data();
74 
75  uchar out [ 100 ]; // Assume the plaintext is < 99 characters
76  uchar final [ 100 ];
77 
78  int ol;
79  EVP_CIPHER_CTX ctx;
80 
81  EVP_DecryptInit ( &ctx, EVP_aes_128_cbc(), key, iv_ptr );
82  EVP_DecryptUpdate( &ctx, out, &ol, cipher_ptr, cipher_ba.size() );
83  EVP_DecryptFinal ( &ctx, final, &ol );
84 
85  QByteArray final_ba( (char*)final, ol );
86 
87  return final_ba;
88 }