-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcryptfiledevice.cpp
More file actions
1075 lines (954 loc) · 28.6 KB
/
Copy pathcryptfiledevice.cpp
File metadata and controls
1075 lines (954 loc) · 28.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//------------------------------------------------------------------------------
// Home Office
// Nürnberg, Germany
// E-Mail: sergej1@email.ua
//
// Copyright (C) 2017/2018 free Project Crypto. All rights reserved.
//------------------------------------------------------------------------------
// Project: Crypto - Advanced File Encryptor, based on simple XOR and
// reliable AES methods
//------------------------------------------------------------------------------
/**
* @file cryptfiledevice.cpp
*
* @brief This file contains the definition of methods and interfaces of the CryptFileDevice class.
*/
//------------------------------------------------------------------------------
// Includes
//------------------------------------------------------------------------------
#include "cryptfiledevice.h"
#include <openssl/evp.h>
#include <limits>
#include <QtEndian>
#include <QDataStream>
#include <QFileDevice>
#include <QFile>
#include <QCryptographicHash>
#include <QLoggingCategory>
//------------------------------------------------------------------------------
// Types
//------------------------------------------------------------------------------
/// file header size. in bytes
static int const kHeaderLength = 0;
/// @todo develop the concept of headers for coded files.
//static int const kHeaderLength = 128;
static int const kHashLength = 32;
static int const kPaddingLength = 54;
/// restriction on the length of the salt.
static int const kSaltMaxLength = 8;
Q_LOGGING_CATEGORY(cryptFileDev, "CryptDev")
/**
* @brief The default constructor of the class CryptFileDevice
*
* The constructor sets default I/O interface parameters.
*
* @param parent of the type QObject*, sets a parent
*/
CryptFileDevice::CryptFileDevice( QObject *parent ) :
QIODevice( parent )
{
}
/**
* @brief The constructor of the class CryptFileDevice
*
* The constructor accepts a read/write device as a parameter.
*
* @param device of the type QFileDevice*, a read/write device
* @param parent of the type QObject*, sets a parent
*/
CryptFileDevice::CryptFileDevice( QFileDevice *device, QObject *parent ) :
QIODevice( parent ),
m_device( device )
{
}
/**
* @brief The constructor of the class CryptFileDevice
*
* The constructor accepts a read/write device as a parameter, as well as a password and a salt.
*
* @param device of the type QFileDevice*, a read/write device
* @param password of the type QByteArray &, sets a password
* @param salt of the type QByteArray &, sets a salt
* @param parent of the type QObject*, sets a parent
*/
CryptFileDevice::CryptFileDevice( QFileDevice *device,
const QByteArray &password,
const QByteArray &salt,
QObject *parent ) :
QIODevice( parent ),
m_device( device ),
m_password( password ),
m_salt( salt.mid( 0, kSaltMaxLength ) ),
m_encMethod( AesCipher )
{
}
/**
* @brief The constructor of the class CryptFileDevice
*
* The constructor accepts a name of the file as a parameter, as well as a password and a salt.
*
* @param fileName of the type QString &, name of the file
* @param password of the type QByteArray &, sets a password
* @param salt of the type QByteArray &, sets a salt
* @param parent of the type QObject*, sets a parent
*/
CryptFileDevice::CryptFileDevice( const QString &fileName,
const QByteArray &password,
const QByteArray &salt,
QObject *parent ) :
QIODevice( parent ),
m_device( new QFile( fileName ) ),
m_deviceOwner( true ),
m_password( password ),
m_salt( salt.mid( 0, kSaltMaxLength ) ),
m_encMethod( AesCipher )
{
}
/**
* @brief The destructor of the class CryptFileDevice
*/
CryptFileDevice::~CryptFileDevice()
{
this->close();
if ( m_deviceOwner )
{
delete m_device;
}
}
/**
* @brief set-function for the Password
* @param password of the type QByteArray &
*/
void CryptFileDevice::setPassword( const QByteArray &password )
{
m_password = password;
}
/**
* @brief set-function for the Salt
* @param salt of the type QByteArray &
*/
void CryptFileDevice::setSalt( const QByteArray &salt )
{
m_salt = salt.mid( 0, kSaltMaxLength );
}
/**
* @brief set-function for the keyLength
* @param keyLength of the type CryptFileDevice::AesKeyLength
*/
void CryptFileDevice::setKeyLength( CryptFileDevice::AesKeyLength keyLength )
{
m_aesKeyLength = keyLength;
}
/**
* @brief set-function for the numRounds
* @param numRounds of the type int
*/
void CryptFileDevice::setNumRounds( int numRounds )
{
m_numRounds = numRounds;
}
/**
* @brief set-function for the encryptionMethod
* @param enc of the type CryptFileDevice::EncryptionMethod
*/
void CryptFileDevice::setEncryptionMethod(CryptFileDevice::EncryptionMethod enc)
{
m_encMethod = enc;
}
/**
* @brief CryptFileDevice::open
*
* Opens the device and sets its OpenMode to mode.
* Returns true if successful; otherwise returns false.
*
* @param mode of the flags QIODevice::OpenMode (ReadOnly, WriteOnly, ReadWrite, etc)
* @retval true if successful,
* @retval false otherwise.
*/
bool CryptFileDevice::open( OpenMode mode )
{
if ( m_device == nullptr )
{
return false;
}
if ( this->isOpen() )
{
return false;
}
if ( mode & WriteOnly )
{
mode |= ReadOnly;
}
if ( mode & Append )
{
mode |= ReadWrite;
}
OpenMode deviceOpenMode;
if ( mode == ReadOnly )
{
deviceOpenMode = ReadOnly;
}
else
{
deviceOpenMode = ReadWrite;
}
if ( mode & Truncate )
{
deviceOpenMode |= Truncate;
}
bool ok;
if ( m_device->isOpen() )
{
ok = (m_device->openMode() == deviceOpenMode);
}
else
{
ok = m_device->open(deviceOpenMode);
}
if (!ok)
{
return false;
}
if ( m_password.isEmpty() )
{
this->setOpenMode( mode );
return true;
}
if ( (m_encMethod == AesCipher) && (!initCipher()) )
{
return false;
}
m_encrypted = true;
this->setOpenMode( mode );
/// @todo develop the concept of headers for coded files.
/// - Allow the user to assign a header for the files.
/// - Handle files with and without headers.
qint64 size = m_device->size();
if ( size == 0 && mode != ReadOnly )
{
// this->insertHeader();
}
if ( size > 0 )
{
if ( !this->tryParseHeader() )
{
m_encrypted = false;
m_device->seek(0);
m_device->close();
return false;
}
}
if ( mode & Append )
{
seek( m_device->size() - kHeaderLength );
}
return true;
}
/**
* @brief CryptFileDevice::insertHeader
*
* The method CryptFileDevice::insertHeader allow you to provide the files
* being encoded with a special 1024 bit header (variable kHeaderLength).
* Which contains AES encryption options, as well as a hash of the sum of the password and salt.
*
* @note In the next version, the header of the encrypted file will be backed up with a CRC checksum.
*/
void CryptFileDevice::insertHeader( void )
{
QDataStream ostream( m_device );
ostream << quint8( 0xcd ); // cryptdevice byte
ostream << quint8( 0x01 ); // version
ostream << static_cast<quint32>( m_aesKeyLength ); // aes key length
ostream << static_cast<qint32>( m_numRounds ); // iteration count to use
ostream.writeRawData( QCryptographicHash::hash( m_password, QCryptographicHash::Sha3_256 ), kHashLength );
ostream.writeRawData( QCryptographicHash::hash( m_salt, QCryptographicHash::Sha3_256 ), kHashLength );
ostream.writeRawData( QByteArray( kPaddingLength, char( 0xcd ) ), kPaddingLength ); // padding with 0xcd
}
/**
* @brief CryptFileDevice::tryParseHeader
*
* The CryptFileDevice::tryParseHeader method parses the special 1024-bit header
* (kHeaderLength variable). This will allow you to look up the special AES encryption
* options as well as a hash of the sum of password and salt.
*
* @note In the next version, the header of the encrypted file will be backed up with a CRC checksum.
*
* @retval true if parse successful,
* @retval false otherwise.
*/
bool CryptFileDevice::tryParseHeader( void )
{
QDataStream istream( m_device );
quint8 cdByte;
istream >> cdByte;
if (cdByte != 0xcd)
{
return false;
}
quint8 version;
istream >> version;
if ( version != 0x01 )
{
return false;
}
quint32 aesKeyLength;
istream >> aesKeyLength;
if (static_cast<AesKeyLength>(aesKeyLength) != m_aesKeyLength)
{
return false;
}
qint32 numRounds;
istream >> numRounds;
if (numRounds != m_numRounds)
{
return false;
}
QByteArray hash(kHashLength, '\0');
int read = istream.readRawData(hash.data(), kHashLength);
if (read != kHashLength)
{
return false;
}
QByteArray expectedPasswordHash = QCryptographicHash::hash( m_password, QCryptographicHash::Sha3_256 );
if (hash != expectedPasswordHash)
{
return false;
}
read = istream.readRawData(hash.data(), kHashLength);
if (read != kHashLength)
{
return false;
}
QByteArray expectedSaltHash = QCryptographicHash::hash( m_salt, QCryptographicHash::Sha3_256 );
if (hash != expectedSaltHash)
{
return false;
}
QByteArray padding(kPaddingLength, '\0');
read = istream.readRawData(padding.data(), kPaddingLength);
if (read != kPaddingLength)
{
return false;
}
QByteArray expectedPadding(kPaddingLength, char(0xcd));
return ( padding == expectedPadding );
}
/**
* @brief CryptFileDevice::close
*
* Reimplemented from QIODevice::close().
* Calls CryptFileDevice::flush() and closes the file.
*
* First emits aboutToClose(), then closes the device and sets its OpenMode to NotOpen.
* The error string is also reset.
*
* @note Errors from flush are ignored.
*/
void CryptFileDevice::close( void )
{
if ( !this->isOpen() )
{
return;
}
if ( (openMode() & WriteOnly) || (openMode() & Append) )
{
flush();
}
this->seek(0);
m_device->close();
this->setOpenMode(NotOpen);
if ( m_encrypted )
{
m_encrypted = false;
}
}
/**
* @brief set-function for the fileName
*
* @param fileName of the type QString &
*/
void CryptFileDevice::setFileName( const QString &fileName )
{
if ( m_device )
{
m_device->close();
if ( m_deviceOwner )
{
delete m_device;
}
}
m_device = new QFile( fileName );
m_deviceOwner = true;
}
/**
* @brief get-function for the fileName
*
* @return fileName of the type QString
*/
QString CryptFileDevice::fileName( void ) const
{
if ( m_device != nullptr )
{
return m_device->fileName();
}
return QString();
}
/**
* @brief set-function for the fileDevice
*
* @param device of the type QFileDevice*
*/
void CryptFileDevice::setFileDevice( QFileDevice *device )
{
if ( m_device )
{
m_device->close();
if ( m_deviceOwner )
{
delete m_device;
}
}
m_device = device;
m_deviceOwner = false;
}
/**
* @brief CryptFileDevice::flush
*
* Flushes any buffered data to the file.
* Returns true if successful; otherwise returns false.
*
* @retval true if successful;
* @retval false otherwise.
*/
bool CryptFileDevice::flush( void )
{
return m_device->flush();
}
/**
* @brief CryptFileDevice::isEncrypted
*
* Returns whether the open file is encrypted.
*
* @retval true if encrypted;
* @retval false otherwise.
*/
bool CryptFileDevice::isEncrypted( void ) const
{
return m_encrypted;
}
/**
* @brief CryptFileDevice::readBlock
*
* Reads from the open file into a buffer of length len.
*
* @param len the length of the block
* @param block a Reference to array of bytes
*
* @return readBytes Number of bytes read
*/
qint64 CryptFileDevice::readBlock( qint64 len, QByteArray &block )
{
int length = block.length();
qint64 readBytes = 0;
do
{
qint64 fileRead = m_device->read( block.data() + block.length(), len - readBytes );
if ( fileRead <= 0 )
{
break;
}
readBytes += fileRead;
} while ( readBytes < len );
if ( readBytes == 0 )
{
return 0;
}
QScopedPointer<char> plaintext( decrypt( block.data() + length, readBytes ) );
block.append( plaintext.data(), readBytes );
return readBytes;
}
/**
* @brief CryptFileDevice::readData
*
* Reimplemented from QIODevice::readData()
*
* Reads up to len bytes from the device into data,
* and returns the number of bytes read or -1 if an error occurred.
*
* @note
* - When reimplementing this function it is important that this function
* reads all the required data before returning.
* This is required in order for QDataStream to be able to operate on the class.
* QDataStream assumes all the requested information was read and
* therefore does not retry reading if there was a problem.
* - This function might be called with a len of 0,
* which can be used to perform post-reading operations.
*
* @param data of the type char*
* @param len the length of the data
*
* @return the number of bytes read or -1 if an error occurred.
*/
qint64 CryptFileDevice::readData( char *data, qint64 len )
{
if ( !m_encrypted )
{
return m_device->read( data, len );
}
if ( len == 0 )
{
return m_device->read( data, len );
}
QByteArray ba;
ba.reserve( len );
do
{
qint64 maxSize = len - ba.length();
qint64 size = readBlock(maxSize, ba);
if ( size == 0 )
{
break;
}
} while ( ba.length() < len );
if ( ba.isEmpty() )
{
return 0;
}
memcpy( data, ba.data(), ba.length() );
return ba.length();
}
/**
* @brief CryptFileDevice::writeData
*
* Reimplemented from QIODevice::writeData().
*
* Writes up to length bytes from data to the device.
* Returns the number of bytes written, or -1 if an error occurred.
*
* @note When reimplementing this function it is important that this function
* writes all the data available before returning.
* This is required in order for QDataStream to be able to operate on the class.
* QDataStream assumes all the information was written and therefore does not retry
* writing if there was a problem.
*
* @param data of the type char*
* @param length the length of the data
* @return the number of bytes written, or -1 if an error occurred.
*/
qint64 CryptFileDevice::writeData( const char *data, qint64 length )
{
if ( !m_encrypted )
{
return m_device->write( data, length );
}
QScopedPointer<char, QScopedPointerArrayDeleter<char> > cipherText( this->encrypt( data, length ) );
if ( cipherText.isNull() )
{
return -1;
}
m_device->write( cipherText.data(), length );
if ( m_device->error() != 0 )
{
qCritical(cryptFileDev) << QObject::tr( "Write Error: %1, code: %2" ).arg( m_device->errorString() ).arg( m_device->error() );
emit errorMessage( QObject::tr( "File: %1\nWrite Error: %2" ).arg( m_device->fileName() ).arg( m_device->errorString() ) );
}
return length;
}
/**
* @brief CryptFileDevice::initCtr
*
* Initializes specific parameters for AES encoding.
* And ends up calling the AES_encrypt(const unsigned char *in, unsigned char *out, const AES_KEY *key) function.
*
* @param state of the type CtrState*
* @param iv of the type unsigned char*
*/
void CryptFileDevice::initCtr( CtrState *state, const unsigned char *iv )
{
qint64 position = pos();
state->num = position % AES_BLOCK_SIZE;
memset( state->ecount, 0, sizeof(state->ecount) );
/* Initialise counter in 'ivec' */
qint64 count = position / AES_BLOCK_SIZE;
if ( state->num > 0 )
{
count++;
}
qint64 newCount = count;
if ( newCount > 0 )
{
newCount = qToBigEndian(count);
}
int sizeOfIv = sizeof( state->ivec ) - sizeof( qint64 );
memcpy( state->ivec + sizeOfIv, &newCount, sizeof( newCount ) );
/* Copy IV into 'ivec' */
memcpy( state->ivec, iv, sizeOfIv );
if ( count > 0 )
{
count = qToBigEndian( count - 1 );
unsigned char prevIvec[ AES_BLOCK_SIZE ];
memcpy( prevIvec, state->ivec, sizeOfIv );
memcpy( prevIvec + sizeOfIv, &count, sizeof( count ) );
AES_encrypt( prevIvec, state->ecount, &m_aesKey );
}
}
/**
* @brief CryptFileDevice::initCipher
*
* This function is required to check the plausibility of the entered keys and parameters.
* Prepares the IV from various parameters and calls the OpenSSL library function EVP_BytesToKey().
*
* int EVP_BytesToKey( const EVP_CIPHER *type,const EVP_MD *md,
* const unsigned char *salt,
* const unsigned char *data, int datal, int count,
* unsigned char *key,unsigned char *iv);
*
* EVP_BytesToKey() derives a key and IV from various parameters.
* - type is the cipher to derive the key and IV for.
* - md is the message digest to use.
* - The salt parameter is used as a salt in the derivation: it should point to an 8 byte buffer or NULL if no salt is used.
* - data is a buffer containing datal bytes which is used to derive the keying data.
* - count is the iteration count to use.
* - The derived key and IV will be written to key and iv respectively.
* .
* Return values:
* If data is NULL, then EVP_BytesToKey() returns the number of bytes needed to store the derived key.
* Otherwise, EVP_BytesToKey() returns the size of the derived key in bytes, or 0 on error.
*
* @note
* - A typical application of this function is to derive keying material for an encryption algorithm from a password in the data parameter.
* - Increasing the count parameter slows down the algorithm which makes it harder for an attacker to peform a brute force attack using a large number of candidate passwords.
* - If the total key and IV length is less than the digest length and MD5 is used then the derivation algorithm is compatible with PKCS#5 v1.5 otherwise a non standard extension is used to derive the extra data.
* - Newer applications should use a more modern algorithm such as PBKDF2 as defined in PKCS#5v2.1 and provided by PKCS5_PBKDF2_HMAC.
* .
* @retval true if success;
* @retval false otherwise.
*/
bool CryptFileDevice::initCipher( void )
{
const EVP_CIPHER *cipher = EVP_enc_null();
if ( m_aesKeyLength == AesKeyLength::kAesKeyLength128 )
{
cipher = EVP_aes_128_ctr();
}
else if ( m_aesKeyLength == AesKeyLength::kAesKeyLength192 )
{
cipher = EVP_aes_192_ctr();
}
else if ( m_aesKeyLength == AesKeyLength::kAesKeyLength256 )
{
cipher = EVP_aes_256_ctr();
}
else
{
Q_ASSERT_X( false, Q_FUNC_INFO, "Unknown value of AesKeyLength" );
}
EVP_CIPHER_CTX ctx;
EVP_CIPHER_CTX_init( &ctx );
EVP_EncryptInit_ex( &ctx, cipher, nullptr, nullptr, nullptr );
int keyLength = EVP_CIPHER_CTX_key_length( &ctx );
int ivLength = EVP_CIPHER_CTX_iv_length( &ctx );
unsigned char key[ keyLength ];
unsigned char iv[ ivLength ];
int ok = EVP_BytesToKey( cipher,
EVP_sha256(),
m_salt.isEmpty() ? nullptr : reinterpret_cast<unsigned char *>(m_salt.data()),
reinterpret_cast<unsigned char *>(m_password.data()),
m_password.length(),
m_numRounds,
key,
iv );
EVP_CIPHER_CTX_cleanup( &ctx );
if ( ok == 0 )
{
return false;
}
int res = AES_set_encrypt_key( key, keyLength * 8, &m_aesKey );
if ( res != 0 )
{
return false;
}
initCtr( &m_ctrState, iv );
return true;
}
/**
* @brief CryptFileDevice::encrypt
* @param plainText
* @param length
* @return
*/
char *CryptFileDevice::encrypt( const char *plainText, qint64 length )
{
unsigned char *cipherText = new (std::nothrow) unsigned char[length];
if ( cipherText == nullptr )
{
qCritical(cryptFileDev) << QObject::tr( "Operator new: bad allocation memory, execution terminating" );
emit errorMessage( QObject::tr( "Bad allocation memory, execution terminating.\n"
"Advice: try to reduce the size of the buffer!" ) );
return nullptr;
}
if ( m_encMethod == AesCipher )
{
AES_ctr128_encrypt(reinterpret_cast<const unsigned char *>(plainText),
cipherText,
length,
&m_aesKey,
m_ctrState.ivec,
m_ctrState.ecount,
&m_ctrState.num);
}
else if ( m_encMethod == XorCipher )
{
QByteArray passwordHash = QCryptographicHash::hash( m_password, QCryptographicHash::Sha3_512 );
unsigned char *pass = reinterpret_cast<unsigned char *>( passwordHash.data() );
for ( qint64 i = 0; i < length; i++ )
{
*(cipherText + i) = *(plainText + i) ^ *(pass + i%64) ^ i%251;
}
}
else
{
Q_ASSERT_X( false, Q_FUNC_INFO, "Unknown value of EncryptionMethod" );
}
return reinterpret_cast<char *>( cipherText );
}
/**
* @brief CryptFileDevice::decrypt
* @param cipherText
* @param len
* @return
*/
char *CryptFileDevice::decrypt( const char *cipherText, qint64 len )
{
unsigned char *plainText = new unsigned char[ len ];
qint64 processLen = 0;
do {
int maxPlainLen = len > std::numeric_limits<int>::max() ? std::numeric_limits<int>::max() : len;
AES_ctr128_encrypt(reinterpret_cast<const unsigned char *>(cipherText) + processLen,
plainText + processLen,
maxPlainLen,
&m_aesKey,
m_ctrState.ivec,
m_ctrState.ecount,
&m_ctrState.num);
processLen += maxPlainLen;
len -= maxPlainLen;
} while ( len > 0 );
return reinterpret_cast<char *>( plainText );
}
/**
* @brief CryptFileDevice::atEnd
*
* Returns true if the current read and write position is at the end of the device
* (i.e. there is no more data available for reading on the device);
* otherwise returns false.
*
* @retval true if the current read and write position is at the end of the device;
* @retval false otherwise.
*
* @warning For some devices, atEnd() can return true even though there is more data to read.
* This special case only applies to devices that generate data in direct response to you calling read()
* (e.g., /dev or /proc files on Unix and OS X, or console input / stdin on all platforms).
*/
bool CryptFileDevice::atEnd( void ) const
{
return QIODevice::atEnd();
}
/**
* @brief CryptFileDevice::bytesAvailable
*
* Returns the number of bytes that are available for reading.
* This function is commonly used with sequential devices to determine the number of bytes to allocate in a buffer before reading.
*
* @note Subclasses that reimplement this function must call the base implementation in order to include the size of the buffer of QIODevice.
* Example:
* @code
* qint64 CustomDevice::bytesAvailable() const
* {
return buffer.size() + QIODevice::bytesAvailable();
* }
* @endcode
*
* @return Returns the number of bytes that are available for reading.
*/
qint64 CryptFileDevice::bytesAvailable( void ) const
{
return QIODevice::bytesAvailable();
}
/**
* @brief CryptFileDevice::pos
*
* For random-access devices, this function returns the position that data is written to or read from.
* For sequential devices or closed devices, where there is no concept of a "current position", 0 is returned.
*
* @note The current read/write position of the device is maintained internally by QIODevice,
* so reimplementing this function is not necessary.
* When subclassing QIODevice, use QIODevice::seek() to notify QIODevice about changes in the device position.
*
* @return returns the position that data is written to or read from.
* For sequential devices or closed devices, where there is no concept of a "current position", 0 is returned.
*/
qint64 CryptFileDevice::pos( void ) const
{
return QIODevice::pos();
}
/**
* @brief CryptFileDevice::seek
*
* For random-access devices, this function sets the current position to pos,
* returning true on success, or false if an error occurred. For sequential devices,
* the default behavior is to produce a warning and return false.
*
* Do not forget that you need to take into account the header of the encoded file.
* The size of which is stored in the constant kHeaderLength.
*
* @note Seeking beyond the end of a file:
* If the position is beyond the end of a file, then seek() will not immediately extend the file.
* If a write is performed at this position, then the file will be extended.
* The content of the file between the previous end of file and
* the newly written data is UNDEFINED and varies between platforms and file systems.
*
* @param pos of the type qint64
* @retval true if success,
* @retval false if an error occurred.
*/
bool CryptFileDevice::seek( qint64 pos )
{
bool result = QIODevice::seek( pos );
if ( m_encrypted )
{
m_device->seek( kHeaderLength + pos );
initCtr(&m_ctrState, m_ctrState.ivec);
}
else
{
m_device->seek(pos);
}
return result;
}
/**
* @brief CryptFileDevice::size
*
* Reimplemented from QIODevice::size().
*
* For open random-access devices, this function returns the size of the device.
* For open sequential devices, bytesAvailable() is returned.
* If the device is closed, the size returned will not reflect the actual size of the device.
*
* @note For regular empty files on Unix (e.g. those in /proc), this function returns 0;
* the contents of such a file are generated on demand in response to you calling read().
*
* @note Do not forget that you need to take into account the header of the encoded file.
* The size of which is stored in the constant kHeaderLength.
*
* @return the size of the file.
*/
qint64 CryptFileDevice::size( void ) const
{
if ( m_device == nullptr )
{
return 0;
}
if ( !m_encrypted )
{
return m_device->size();
}
return m_device->size() - kHeaderLength;
}
/**
* @brief CryptFileDevice::remove
*
* Removes the file specified by fileName(). Returns true if successful;
* otherwise returns false.
*
* @note The file is closed before it is removed.
*
* @retval true if successful;
* @retval false otherwise.
*/
bool CryptFileDevice::remove( void )
{
if ( m_device == nullptr )
{
return false;
}
QString fileName = m_device->fileName();
if ( fileName.isEmpty() )
{
return false;
}
if ( this->isOpen() )
{
close();
}
bool ok = QFile::remove( fileName );
if ( ok )
{
m_device = nullptr;
}