-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathidxcrypt.cpp
1313 lines (1108 loc) · 37 KB
/
idxcrypt.cpp
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
/*
* A small utility to encrypt/decrypt files using AES256 and strong password key derivation.
*
* The AES256 key is derived from password using PBKDF2 with 500000 iterations.
*
* All cryptographic operations are done using Windows Crypto API.
*
* Copyright (c) 2014-2016 Mounir IDRASSI <[email protected]>. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#ifndef _WIN32_WINNT
#define _WIN32_WINNT 0x0501 /* Windows XP minimum */
#endif
#ifndef NTDDI_VERSION
#define NTDDI_VERSION 0x05010300 /* XP SP3 minimum */
#endif
#ifndef UNICODE
#define UNICODE
#endif
#ifndef _UNICODE
#define _UNICODE
#endif
#ifndef _CRT_SECURE_NO_WARNINGS
#define _CRT_SECURE_NO_WARNINGS
#endif
#include <windows.h>
#include <wincrypt.h>
#include <stdio.h>
#include <io.h>
#include <math.h>
#include <time.h>
#include <tchar.h>
#include <string.h>
#include <iostream>
#include <string>
#include <Shlwapi.h>
#pragma comment(lib, "Shlwapi.lib")
using namespace std;
#define MAX 32767
#ifndef MS_ENH_RSA_AES_PROV_XP
#define MS_ENH_RSA_AES_PROV_XP L"Microsoft Enhanced RSA and AES Cryptographic Provider (Prototype)"
#endif
#define STRONG_ITERATIONS 500000
#define READ_BUFFER_SIZE 65536
// Pseudo Random Function (PRF) prototype
/* generic context used in HMAC calculation */
#define PRF_CTX_MAGIC 0x50524643
typedef struct
{
DWORD magic; /* used to help check that we are using the correct context */
DWORD digestSize; /* digest size in bytes of the underlying hash algorithm */
void* pParam; /* hold a custom pointer known to the implementation */
} PRF_CTX;
typedef BOOL (WINAPI* PRF_HmacInitPtr)(
PRF_CTX* pContext, /* PRF context used in HMAC computation */
unsigned char* pbKey, /* pointer to authentication key */
DWORD cbKey /* length of authentication key */
);
typedef BOOL (WINAPI* PRF_HmacPtr)(
PRF_CTX* pContext, /* PRF context initialized by HmacInit */
unsigned char* pbData, /* pointer to data stream */
DWORD cbData, /* length of data stream */
unsigned char* pbDigest /* caller digest to be filled in */
);
typedef BOOL (WINAPI* PRF_HmacFreePtr)(
PRF_CTX* pContext /* PRF context initialized by HmacInit */
);
/* PRF type definition */
typedef struct
{
PRF_HmacInitPtr hmacInit;
PRF_HmacPtr hmac;
PRF_HmacFreePtr hmacFree;
} PRF;
/* Implementation of HMAC using CAPI */
typedef struct
{
HCRYPTPROV hProv;
HCRYPTHASH hInnerHash;
HCRYPTHASH hOuterHash;
} CAPI_CTX_PARAM;
// Structure used by CAPI for HMAC computation
typedef struct {
BLOBHEADER hdr;
DWORD cbKeySize;
} HMAC_KEY_BLOB;
BOOL WINAPI hmacGenericInit(
PRF_CTX* pContext, /* PRF context used in HMAC computation */
ALG_ID hashAlgid, /* hash algorithm used in HMAC */
unsigned char* pbKey, /* pointer to authentication key */
DWORD cbKey /* length of authentication key */
)
{
HCRYPTPROV hProv = NULL;
HCRYPTHASH hHash = NULL, hInnerHash = NULL, hOuterHash = NULL;
DWORD cbDigestSize, cbBlockSize;
BOOL bStatus = FALSE;
DWORD dwError = 0, i;
BYTE key[64];
BYTE buffer[128];
switch (hashAlgid)
{
case CALG_SHA1: cbDigestSize = 20; cbBlockSize = 64; break;
case CALG_SHA_256: cbDigestSize = 32; cbBlockSize = 64; break;
case CALG_SHA_384: cbDigestSize = 48; cbBlockSize = 128; break;
case CALG_SHA_512: cbDigestSize = 64; cbBlockSize = 128; break;
default: return FALSE;
}
if (!pContext)
{
dwError = ERROR_BAD_ARGUMENTS;
goto hmacInit_end;
}
if (!CryptAcquireContext(&hProv, NULL, MS_ENH_RSA_AES_PROV, PROV_RSA_AES, CRYPT_VERIFYCONTEXT))
{
if (!CryptAcquireContext(&hProv, NULL, MS_ENH_RSA_AES_PROV_XP, PROV_RSA_AES, CRYPT_VERIFYCONTEXT))
{
dwError = GetLastError();
goto hmacInit_end;
}
}
if ( !CryptCreateHash (hProv, hashAlgid, NULL, 0, &hHash)
|| !CryptCreateHash (hProv, hashAlgid, NULL, 0, &hInnerHash)
|| !CryptCreateHash (hProv, hashAlgid, NULL, 0, &hOuterHash)
)
{
dwError = GetLastError();
goto hmacInit_end;
}
if (cbKey > cbBlockSize)
{
/* If key is larger than hash algorithm block size,
* set key = hash(key) as per HMAC specifications.
*/
if (!CryptHashData (hHash, pbKey, cbKey, 0))
{
dwError = GetLastError();
goto hmacInit_end;
}
cbKey = sizeof (key);
if (!CryptGetHashParam (hHash, HP_HASHVAL, key, &cbKey, 0))
{
dwError = GetLastError();
goto hmacInit_end;
}
pbKey = key;
}
/* Precompute HMAC Inner Digest */
for (i = 0; i < cbKey; ++i)
buffer[i] = (char) (pbKey[i] ^ 0x36);
memset (&buffer[cbKey], 0x36, cbBlockSize - cbKey);
if (!CryptHashData (hInnerHash, buffer, cbBlockSize, 0))
{
dwError = GetLastError();
goto hmacInit_end;
}
/* Precompute HMAC Outer Digest */
for (i = 0; i < cbKey; ++i)
buffer[i] = (char) (pbKey[i] ^ 0x5C);
memset (&buffer[cbKey], 0x5C, cbBlockSize - cbKey);
if (!CryptHashData (hOuterHash, buffer, cbBlockSize, 0))
{
dwError = GetLastError();
goto hmacInit_end;
}
CAPI_CTX_PARAM* pParam = (CAPI_CTX_PARAM*) LocalAlloc(0, sizeof(CAPI_CTX_PARAM));
pParam->hProv = hProv;
pParam->hInnerHash = hInnerHash;
pParam->hOuterHash = hOuterHash;
pContext->magic = PRF_CTX_MAGIC;
pContext->digestSize = cbDigestSize;
pContext->pParam = (void*) pParam;
hProv = NULL;
hInnerHash = NULL;
hOuterHash = NULL;
bStatus = TRUE;
hmacInit_end:
if (hHash) CryptDestroyHash(hHash);
if (hInnerHash) CryptDestroyHash(hInnerHash);
if (hOuterHash) CryptDestroyHash(hOuterHash);
if (hProv) CryptReleaseContext(hProv, 0);
SetLastError(dwError);
return bStatus;
}
BOOL WINAPI hmacGeneric(
PRF_CTX* pContext, /* PRF context used in HMAC computation */
unsigned char* pbData, /* pointer to data stream */
DWORD cbData, /* length of data stream */
unsigned char* pbDigest /* caller digest to be filled in */
)
{
HCRYPTPROV hProv = NULL;
HCRYPTHASH hHash = NULL;
HCRYPTHASH hInnerHash = NULL;
HCRYPTHASH hOuterHash = NULL;
DWORD cbDigest = 0;
BOOL bStatus = FALSE;
DWORD dwError = 0;
if (!pContext || (pContext->magic != PRF_CTX_MAGIC) || (!pContext->pParam))
{
dwError = ERROR_BAD_ARGUMENTS;
goto hmac_end;
}
hProv = ((CAPI_CTX_PARAM*) pContext->pParam)->hProv;
hInnerHash = ((CAPI_CTX_PARAM*) pContext->pParam)->hInnerHash;
hOuterHash = ((CAPI_CTX_PARAM*) pContext->pParam)->hOuterHash;
/* Restore Precomputed Inner Digest Context */
if (!CryptDuplicateHash( hInnerHash, NULL, 0, &hHash))
{
dwError = GetLastError();
goto hmac_end;
}
if (!CryptHashData(hHash, pbData, cbData, 0))
{
dwError = GetLastError();
goto hmac_end;
}
cbDigest = pContext->digestSize;
if (!CryptGetHashParam(hHash, HP_HASHVAL, pbDigest, &cbDigest, 0))
{
dwError = GetLastError();
goto hmac_end;
}
CryptDestroyHash(hHash);
hHash = NULL;
/* Restore Precomputed Outer Digest Context */
if (!CryptDuplicateHash( hOuterHash, NULL, 0, &hHash))
{
dwError = GetLastError();
goto hmac_end;
}
if (!CryptHashData(hHash, pbDigest, cbDigest, 0))
{
dwError = GetLastError();
goto hmac_end;
}
cbDigest = pContext->digestSize;
if (!CryptGetHashParam(hHash, HP_HASHVAL, pbDigest, &cbDigest, 0))
{
dwError = GetLastError();
goto hmac_end;
}
bStatus = TRUE;
hmac_end:
if (hHash) CryptDestroyHash(hHash);
SetLastError(dwError);
return bStatus;
}
BOOL WINAPI hmacGenericFree(
PRF_CTX* pContext /* PRF context used in HMAC computation */
)
{
HCRYPTPROV hProv = NULL;
HCRYPTHASH hInnerHash = NULL;
HCRYPTHASH hOuterHash = NULL;
if (!pContext || (pContext->magic != PRF_CTX_MAGIC) || (!pContext->pParam))
{
SetLastError(ERROR_BAD_ARGUMENTS);
return FALSE;
}
hProv = ((CAPI_CTX_PARAM*) pContext->pParam)->hProv;
hInnerHash = ((CAPI_CTX_PARAM*) pContext->pParam)->hInnerHash;
hOuterHash = ((CAPI_CTX_PARAM*) pContext->pParam)->hOuterHash;
CryptDestroyKey(hInnerHash);
CryptDestroyKey(hOuterHash);
CryptReleaseContext(hProv, 0);
LocalFree(pContext->pParam);
SecureZeroMemory(pContext, sizeof(PRF_CTX));
return TRUE;
}
/*
* Definition of the HMAC PRF objects
*/
static BOOL WINAPI hmacInit_sha1( PRF_CTX* pContext, unsigned char* pbKey, DWORD cbKey)
{
return hmacGenericInit (pContext, CALG_SHA1, pbKey, cbKey);
}
static BOOL WINAPI hmacInit_sha256( PRF_CTX* pContext, unsigned char* pbKey, DWORD cbKey)
{
return hmacGenericInit (pContext, CALG_SHA_256, pbKey, cbKey);
}
static BOOL WINAPI hmacInit_sha384( PRF_CTX* pContext, unsigned char* pbKey, DWORD cbKey)
{
return hmacGenericInit (pContext, CALG_SHA_384, pbKey, cbKey);
}
static BOOL WINAPI hmacInit_sha512( PRF_CTX* pContext, unsigned char* pbKey, DWORD cbKey)
{
return hmacGenericInit (pContext, CALG_SHA_512, pbKey, cbKey);
}
PRF sha1Prf = {hmacInit_sha1, hmacGeneric, hmacGenericFree};
PRF sha256Prf = {hmacInit_sha256, hmacGeneric, hmacGenericFree};
PRF sha384Prf = {hmacInit_sha384, hmacGeneric, hmacGenericFree};
PRF sha512Prf = {hmacInit_sha512, hmacGeneric, hmacGenericFree};
static inline void xor(LPBYTE ptr1, LPBYTE ptr2, DWORD dwLen)
{
if (dwLen)
while (dwLen--) *ptr1++ ^= *ptr2++;
}
/*
* PBKDF2 implementation
*/
BOOL PBKDF2(PRF pPrf,
unsigned char* pbPassword,
DWORD cbPassword,
unsigned char* pbSalt,
DWORD cbSalt,
DWORD dwIterationCount,
unsigned char* pbDerivedKey,
DWORD cbDerivedKey)
{
BOOL bStatus = FALSE;
DWORD dwError = 0;
DWORD l, r, i,j;
DWORD hlen;
LPBYTE Ti = NULL;
LPBYTE V = NULL;
LPBYTE U = NULL;
DWORD dwULen;
PRF_CTX prfCtx = {0};
if (!pbDerivedKey || !cbDerivedKey || (!pbPassword && cbPassword) )
{
dwError = ERROR_BAD_ARGUMENTS;
goto PBKDF2_end;
}
if (!pPrf.hmacInit(&prfCtx, pbPassword, cbPassword))
{
dwError = GetLastError();
goto PBKDF2_end;
}
hlen = prfCtx.digestSize;
Ti = (LPBYTE) LocalAlloc(0, hlen);
V = (LPBYTE) LocalAlloc(0, hlen);
U = (LPBYTE) LocalAlloc(0, max((cbSalt + 4), hlen));
if (!Ti || !U || !V)
{
dwError = ERROR_NOT_ENOUGH_MEMORY;
goto PBKDF2_end;
}
l = (DWORD) ceil((double) cbDerivedKey / (double) hlen);
r = cbDerivedKey - (l - 1) * hlen;
for (i = 1; i <= l; i++)
{
ZeroMemory(Ti, hlen);
for (j = 0; j < dwIterationCount; j++)
{
if (j == 0)
{
// construct first input for PRF
memcpy(U, pbSalt, cbSalt);
U[cbSalt] = (BYTE) ((i & 0xFF000000) >> 24);
U[cbSalt + 1] = (BYTE) ((i & 0x00FF0000) >> 16);
U[cbSalt + 2] = (BYTE) ((i & 0x0000FF00) >> 8);
U[cbSalt + 3] = (BYTE) ((i & 0x000000FF));
dwULen = cbSalt + 4;
}
else
{
memcpy(U, V, hlen);
dwULen = hlen;
}
if (!pPrf.hmac(&prfCtx, U, dwULen, V))
{
dwError = GetLastError();
goto PBKDF2_end;
}
xor(Ti, V, hlen);
}
if (i != l)
{
memcpy(&pbDerivedKey[(i-1) * hlen], Ti, hlen);
}
else
{
// Take only the first r bytes
memcpy(&pbDerivedKey[(i-1) * hlen], Ti, r);
}
}
bStatus = TRUE;
PBKDF2_end:
pPrf.hmacFree(&prfCtx);
if (Ti) LocalFree(Ti);
if (U) LocalFree(U);
if (V) LocalFree(V);
SetLastError(dwError);
return bStatus;
}
BOOL GenerateRandom(LPBYTE pbRand, DWORD cbRand)
{
HCRYPTPROV hProv;
BOOL bRet = CryptAcquireContext(&hProv, NULL, MS_ENHANCED_PROV, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT);
if (bRet)
{
bRet = CryptGenRandom(hProv, cbRand, pbRand);
CryptReleaseContext(hProv, 0);
}
return bRet;
}
BOOL ImportKeyData(HCRYPTPROV hProvider, ALG_ID Algid, BYTE *pbKeyData, DWORD cbKeyData, HCRYPTKEY* phKey)
{
BOOL bResult = FALSE;
BYTE *pbData = 0;
DWORD cbData, cbHeaderLen, cbKeyLen, dwDataLen;
ALG_ID *pAlgid;
HCRYPTKEY hImpKey = 0;
BLOBHEADER *pBlob;
if (!CryptGetUserKey(hProvider, AT_KEYEXCHANGE, &hImpKey)) {
if (GetLastError( ) != NTE_NO_KEY) goto done;
if (!CryptGenKey(hProvider, AT_KEYEXCHANGE, (1024 << 16), &hImpKey))
goto done;
}
cbData = cbKeyData;
cbHeaderLen = sizeof(BLOBHEADER) + sizeof(ALG_ID);
if (!CryptEncrypt(hImpKey, 0, TRUE, 0, 0, &cbData, cbData)) goto done;
if (!(pbData = (BYTE *)LocalAlloc(LMEM_FIXED, cbData + cbHeaderLen)))
goto done;
CopyMemory(pbData + cbHeaderLen, pbKeyData, cbKeyData);
cbKeyLen = cbKeyData;
if (!CryptEncrypt(hImpKey, 0, TRUE, 0, pbData + cbHeaderLen, &cbKeyLen, cbData))
goto done;
pBlob = (BLOBHEADER *)pbData;
pAlgid = (ALG_ID *)(pbData + sizeof(BLOBHEADER));
pBlob->bType = SIMPLEBLOB;
pBlob->bVersion = 2;
pBlob->reserved = 0;
pBlob->aiKeyAlg = Algid;
dwDataLen = sizeof(ALG_ID);
if (!CryptGetKeyParam(hImpKey, KP_ALGID, (BYTE *)pAlgid, &dwDataLen, 0))
goto done;
bResult = CryptImportKey(hProvider, pbData, cbData + cbHeaderLen, hImpKey, 0,
phKey);
if (bResult) SecureZeroMemory(pbKeyData, cbKeyData);
done:
if (pbData) LocalFree(pbData);
CryptDestroyKey(hImpKey);
return bResult;
}
typedef struct
{
HCRYPTPROV hProv;
HCRYPTKEY hKey;
BOOL bForDecrypt;
} AES_CTX;
BOOL AesInit(LPBYTE pbKey, LPBYTE pbIV, BOOL bForDecrypt, AES_CTX* pCtx)
{
BOOL bRet = CryptAcquireContext(&pCtx->hProv, NULL, MS_ENH_RSA_AES_PROV, PROV_RSA_AES, CRYPT_VERIFYCONTEXT);
if (!bRet)
bRet = CryptAcquireContext(&pCtx->hProv, NULL, MS_ENH_RSA_AES_PROV_XP, PROV_RSA_AES, CRYPT_VERIFYCONTEXT);
if (bRet)
{
bRet = ImportKeyData(pCtx->hProv, CALG_AES_256, pbKey, 32, &pCtx->hKey);
if (bRet)
{
DWORD dwMode = CRYPT_MODE_CBC;
bRet = CryptSetKeyParam(pCtx->hKey, KP_MODE, (BYTE *)&dwMode, 0);
if (bRet)
bRet = CryptSetKeyParam(pCtx->hKey, KP_IV, pbIV, 0);
if (!bRet)
CryptDestroyKey(pCtx->hKey);
}
if (!bRet)
CryptReleaseContext(pCtx->hProv, 0);
}
pCtx->bForDecrypt = bForDecrypt;
return bRet;
}
BOOL AesProcess(AES_CTX* pCtx, LPBYTE pbData, LPDWORD pcbData, DWORD cbBuffer, BOOL bFinal)
{
BOOL bRet;
if (pCtx->bForDecrypt)
bRet = CryptDecrypt(pCtx->hKey, NULL, bFinal, 0, pbData, pcbData);
else
bRet = CryptEncrypt(pCtx->hKey, NULL, bFinal, 0, pbData, pcbData, cbBuffer);
return bRet;
}
/* Function to display information about the progress of the current operation */
clock_t startClock = 0;
clock_t currentClock = 0;
void ShowProgress (LPCTSTR szOperationDesc, __int64 inputLength, __int64 totalProcessed, BOOL bFinalBlock)
{
/* display progress information every 2 seconds */
clock_t t = clock();
if ((currentClock == 0) || bFinalBlock || ((t - currentClock) >= (2 * CLOCKS_PER_SEC)))
{
currentClock = t;
if (currentClock == startClock) currentClock = startClock + 1;
double processingTime = (double) (currentClock - startClock) / (double) CLOCKS_PER_SEC;
if (bFinalBlock)
_tprintf(_T("\r%sDone! (time: %.2fs - speed: %.2f MiB/s)\n"), szOperationDesc, processingTime, (double) totalProcessed / (processingTime * 1024.0 * 1024.0));
else
_tprintf(_T("\r%s (%.2f%% - %.2f MiB/s)"), szOperationDesc, ((double) totalProcessed * 100.0)/ (double) inputLength, (double) totalProcessed / (processingTime * 1024.0 * 1024.0));
}
}
void ShowUsage()
{
_tprintf(_T("Usage to encrypt an entire folder : idxcrypt InputFolder Password OutputFolder [/d] [/hash algo]\n"));
_tprintf(_T("\tInputFolder example : C:\\inputFolder (absolute path) or inputFolder (relative path) \n"));
_tprintf(_T("\tOutputFolder example : C:\\outputFolder (absolute path) or outputFolder (relative path) \n\n"));
_tprintf(_T("Usage to encrypt a file : idxcrypt InputFile Password OutputFile [/d] [/hash algo]\n"));
_tprintf(_T("\tInputFile example : C:\\inputFile (absolute path) or inputFile (relative path) \n"));
_tprintf(_T("\tOutputFile example : C:\\outputFile (absolute path) or outputFile (relative path)\n"));
_tprintf(_T("\tParameters:\n"));
_tprintf(_T("\t /d: Perform decryption instead of encryption\n"));
_tprintf(_T("\t /hash algo: Specified hash algorithm to use for key derivation.\n"));
_tprintf(_T("\t Possible value are sha256, sha384 and sha512.\n"));
_tprintf(_T("\t sha256 is the default\n"));
_tprintf(_T("\n"));
_tprintf(_T("\nPlease use backslashes rather than slashes!\n"));
}
int opFile(FILE* fin, FILE* fout, const WCHAR foutPath[], char szPassword[], BOOL bForDecrypt, PRF* pPrf, size_t cbSalt)
{
BYTE pbDerivedKey[256];
BYTE pbSalt[64], pbIV[16];
BYTE pbData[READ_BUFFER_SIZE + 32];
DWORD cbData;
size_t readLen = 0;
__int64 totalProcessed = 0;
__int64 inputLength;
int iStatus = 0;
inputLength = _filelengthi64(_fileno(fin));
if (bForDecrypt){
if ((cbSalt != fread(pbSalt, 1, cbSalt, fin)) || (16 != fread(pbIV, 1, 16, fin)))
{
_tprintf(_T("An unexpected error occured while reading the input file. Aborting...\n"));
iStatus = -1;
return iStatus;
}
/* remove size of salt and IV from the input length */
inputLength -= (__int64)(16 + cbSalt);
}
else
{
/* generate random salt and IV*/
if (!GenerateRandom(pbSalt, (DWORD)cbSalt) || !GenerateRandom(pbIV, 16))
{
DWORD dwErr = GetLastError();
_tprintf(_T("An unexpected error occured while preparing for the encryption (Code 0x%.8X). Aborting...\n"), dwErr);
iStatus = -1;
return iStatus;
}
}
if (bForDecrypt)
_tprintf(_T("Generating the decryption key..."));
else
_tprintf(_T("Generating the encryption key..."));
if (!PBKDF2(*pPrf, (LPBYTE)szPassword, (DWORD)strlen(szPassword), pbSalt, (DWORD)cbSalt, STRONG_ITERATIONS, pbDerivedKey, 32))
{
if (bForDecrypt)
_tprintf(_T("Error!\nAn unexpected error occured while creating the decryption key (Code 0x%.8X). Aborting...\n"), GetLastError());
else
_tprintf(_T("Error!\nAn unexpected error occured while creating the encryption key (Code 0x%.8X). Aborting...\n"), GetLastError());
iStatus = -1;
}
else
{
if (bForDecrypt)
_tprintf(_T("Done!\nInitializing decryption..."));
else
_tprintf(_T("Done!\nInitializing encryption..."));
AES_CTX ctx;
BOOL bStatus;
if (AesInit(pbDerivedKey, pbIV, bForDecrypt, &ctx))
{
TCHAR szOpDesc[64];
BYTE pbHeader[16];
memcpy(pbHeader, "IDXCRYPTTPYRCXDI", 16);
_tprintf(_T("Done!\n"));
if (bForDecrypt)
_tcscpy(szOpDesc, _T("Decrypting the input file..."));
else
_tcscpy(szOpDesc, _T("Encrypting the input file..."));
_tprintf(szOpDesc);
if (bForDecrypt)
{
cbData = (DWORD)fread(pbData, 1, 16, fin);
/* remove size of header from input length */
inputLength -= 16;
if (cbData == 16)
{
if (AesProcess(&ctx, pbData, &cbData, sizeof(pbData), FALSE))
{
if ((cbData == 16) && (0 == memcmp(pbData, pbHeader, 16)))
{
BOOL bFinal = FALSE;
startClock = clock();
while (!bFinal && ((readLen = fread(pbData, 1, READ_BUFFER_SIZE, fin)) == READ_BUFFER_SIZE))
{
cbData = (DWORD)readLen;
totalProcessed += (__int64)READ_BUFFER_SIZE;
bFinal = (totalProcessed == inputLength) ? TRUE : FALSE;
if (AesProcess(&ctx, pbData, &cbData, sizeof(pbData), bFinal))
{
if (cbData == fwrite(pbData, 1, cbData, fout))
{
ShowProgress(szOpDesc, inputLength, totalProcessed, bFinal);
}
else
{
_tprintf(_T("Not all decrypted bytes were written to disk. Aborting!\n"));
iStatus = -2;
break;
}
}
else
{
iStatus = -3;
_tprintf(_T("\nUnexpected error occured while decrypting data. Aborting!\n"));
break;
}
}
if ((iStatus == 0) && !bFinal)
{
if (ferror(fin))
{
_tprintf(_T("Unexpected error occured while reading data from input file. Aborting!\n"));
iStatus = -1;
}
else
{
cbData = (DWORD)readLen;
totalProcessed += (__int64)readLen;
if (AesProcess(&ctx, pbData, &cbData, sizeof(pbData), TRUE))
{
if (cbData == fwrite(pbData, 1, cbData, fout))
{
ShowProgress(szOpDesc, inputLength, totalProcessed, TRUE);
}
else
{
_tprintf(_T("Not all decrypted bytes were written to disk. Aborting!\n"));
iStatus = -2;
}
}
else {
_tprintf(_T("Unexpected error occured while decrypting. Aborting!\n"));
iStatus = -3;
}
}
}
}
else
{
_tprintf(_T("Password incorrect or the input file is not a valid encrypted file. Aborting!\n"));
iStatus = -4;
}
}
else
{
_tprintf(_T("Unexpected error occured while decrypting. Aborting\n"));
iStatus = -3;
}
}
else
{
_tprintf(_T("Unexpected error occured while reading data from input file. Aborting\n"));
iStatus = -1;
}
}
else
{
/* write the random salt */
/* write the random IV */
if ((cbSalt !=fwrite(pbSalt, 1, cbSalt, fout)) || (16 != fwrite(pbIV, 1, 16, fout))){
_tprintf(_T("An unexpected error occured while writing data to the output file. Aborting!\n"));
iStatus = -2;
return iStatus;
}
/* protect encryption memory against swaping */
VirtualLock(pbData, sizeof(pbData));
memcpy(pbData, pbHeader, 16);
cbData = 16;
if (AesProcess(&ctx, pbData, &cbData, sizeof(pbData), FALSE))
{
fwrite(pbData, 1, cbData, fout);
startClock = clock();
while ((readLen = fread(pbData, 1, READ_BUFFER_SIZE, fin)) == READ_BUFFER_SIZE)
{
cbData = (DWORD)READ_BUFFER_SIZE;
bStatus = AesProcess(&ctx, pbData, &cbData, sizeof(pbData), FALSE);
if (bStatus)
{
totalProcessed += (__int64)READ_BUFFER_SIZE;
if (cbData == fwrite(pbData, 1, cbData, fout))
{
ShowProgress(szOpDesc, inputLength, totalProcessed, FALSE);
}
else
{
_tprintf(_T("Not all encrypted bytes were written to disk. Aborting!\n"));
iStatus = -2;
break;
}
}
else
{
_tprintf(_T("Unexpected error occured while encrypting. Aborting\n"));
iStatus = -3;
break;
}
}
if (iStatus == 0)
{
if (ferror(fin))
{
_tprintf(_T("Unexpected error occured while reading data from input file. Aborting\n"));
iStatus = -1;
}
else
{
cbData = (DWORD)readLen;
if (AesProcess(&ctx, pbData, &cbData, sizeof(pbData), TRUE))
{
totalProcessed += (__int64)readLen;
if (cbData == fwrite(pbData, 1, cbData, fout))
{
ShowProgress(szOpDesc, inputLength, totalProcessed, TRUE);
}
else
{
_tprintf(_T("Not all encrypted bytes were written to disk. Aborting!\n"));
iStatus = -2;
}
}
else {
_tprintf(_T("Unexpected error occured while encrypting. Aborting\n"));
iStatus = -3;
}
}
}
}
else {
_tprintf(_T("Unexpected error occured while encrypting. Aborting\n"));
iStatus = -3;
}
}
if (iStatus == 0)
{
_tprintf(_T("Flushing output file data to disk, please wait..."));
_tprintf(_T("\rInput file %s successfully as \"%s\"\n"), bForDecrypt ? _T("decrypted") : _T("encrypted"), foutPath);
}
}
else
{
_tprintf(_T("Error! Aborting!\n"));
iStatus = -1;
}
}
return iStatus;
}
int opEncDir(WIN32_FIND_DATA f, HANDLE h, const WCHAR finPath[], const WCHAR foutPath[], char szPassword[], PRF *pPrf, size_t cbSalt)
{
FILE* fin=NULL;
FILE* fout=NULL;
wstring fileName, fileInPath, fileOutPath;
__int64 inputLength;
int iStatus = 0;
do {
fileName = wstring(f.cFileName);
if ((fileName.compare(L".") == 0 && fileName.length() == 1) || (fileName.compare(L"..") == 0 && fileName.length() == 2)) {
if (FindNextFile(h, &f) == 0) break;
continue;
}
if ((f.dwFileAttributes&FILE_ATTRIBUTE_DIRECTORY)!=0) {
fileOutPath = foutPath;
fileOutPath += fileName;
fileOutPath += L"\\";
fileInPath = (wstring(finPath)).substr(0, ((wstring)finPath).length() - 1);
fileInPath += fileName;
fileInPath += L"\\*";
if (!CreateDirectory(fileOutPath.c_str(), NULL) && ERROR_ALREADY_EXISTS != GetLastError()) {
printf("Could not create/open the output folder %ws . (%d). Aborting...\n", fileOutPath.c_str(), GetLastError());
iStatus = -1;
return iStatus;
}
WIN32_FIND_DATA F;
iStatus = opEncDir(F, FindFirstFile(fileInPath.c_str(), &F), fileInPath.c_str(), fileOutPath.c_str(), szPassword, pPrf, cbSalt);
}
else {
fileInPath = (wstring(finPath)).substr(0, ((wstring)finPath).length() - 1);
fileInPath += fileName;
fileOutPath = foutPath;
fileOutPath += fileName;
fileOutPath += L".idx";
fin = _tfopen(fileInPath.c_str(), _T("rb"));
if (!fin)
{
_tprintf(_T("Failed to open the input file (%ws) for reading. Aborting...\n"), fileInPath.c_str());
iStatus = -1;
return iStatus;
}
if ((inputLength = _filelengthi64(_fileno(fin))) == 0)
{
_tprintf(_T("The input file %ws is empty. Aborting...\n"), fileInPath.c_str());
iStatus = -1;
return iStatus;
}
fout = _tfopen(fileOutPath.c_str(), _T("wb"));
if (!fout)
{
_tprintf(_T("Failed to open the output file %ws for writing. Aborting...\n"), fileOutPath.c_str());
iStatus = -1;
return iStatus;
}
iStatus = opFile(fin, fout, fileOutPath.c_str(), szPassword, FALSE, pPrf, cbSalt);
}
if (iStatus != 0) {
return iStatus;
}
if (fout) {
fclose(fout);
fout = NULL;
}
if (FindNextFile(h, &f) == 0) break;
} while (1);
return iStatus;
}
int opDecDir(WIN32_FIND_DATA f, HANDLE h, const WCHAR finPath[], const WCHAR foutPath[], char szPassword[], PRF *pPrf, size_t cbSalt)
{
FILE* fin=NULL;
FILE* fout=NULL;
wstring fileName, fileInPath, fileOutPath;
__int64 inputLength;
int iStatus = 0;
do {
fileName = wstring(f.cFileName);
if ((fileName.compare(L".") == 0 && fileName.length() == 1) || (fileName.compare(L"..") == 0 && fileName.length() == 2)) {
if (FindNextFile(h, &f) == 0) break;
continue;
}
if ((f.dwFileAttributes&FILE_ATTRIBUTE_DIRECTORY)!=0) {
fileOutPath = foutPath;
fileOutPath += fileName;
fileOutPath += L"\\";
fileInPath = (wstring(finPath)).substr(0, (wstring(finPath)).length() - 1);
fileInPath += fileName;
fileInPath += L"\\*";