-
Notifications
You must be signed in to change notification settings - Fork 11
/
DirHash.cpp
3733 lines (3283 loc) · 94.5 KB
/
DirHash.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
/*
* An implementation of directory hashing that uses lexicographical order on name
* for sorting. Based on OpenSSL and Microsoft CNG for hash algorithms for maximum
* performance and compatibility.
*
* Copyright (c) 2010-2024 Mounir IDRASSI <[email protected]>. All rights reserved.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE.
*
*/
#ifndef _WIN32_WINNT
#define _WIN32_WINNT 0x0600
#endif
/* We use UNICODE */
#ifndef UNICODE
#define UNICODE
#endif
#ifndef _UNICODE
#define _UNICODE
#endif
#ifndef ALG_SID_SHA_256
#define ALG_SID_SHA_256 12
#endif
#ifndef ALG_SID_SHA_384
#define ALG_SID_SHA_384 13
#endif
#ifndef ALG_SID_SHA_512
#define ALG_SID_SHA_512 14
#endif
#ifndef CALG_SHA_256
#define CALG_SHA_256 (ALG_CLASS_HASH | ALG_TYPE_ANY | ALG_SID_SHA_256)
#endif
#ifndef CALG_SHA_384
#define CALG_SHA_384 (ALG_CLASS_HASH | ALG_TYPE_ANY | ALG_SID_SHA_384)
#endif
#ifndef CALG_SHA_512
#define CALG_SHA_512 (ALG_CLASS_HASH | ALG_TYPE_ANY | ALG_SID_SHA_512)
#endif
#define _CRT_SECURE_NO_WARNINGS
#pragma warning(disable : 4995)
#include <ntstatus.h>
#define WIN32_NO_STATUS
#include <windows.h>
#include <WinCrypt.h>
#include <bcrypt.h>
#include <Shlwapi.h>
#include <pathcch.h>
#include <stdio.h>
#include <stdarg.h>
#include <tchar.h>
#include <fcntl.h>
#include <io.h>
#include <time.h>
#include <strsafe.h>
#if !defined (_M_ARM64) && !defined (_M_ARM)
#include "BLAKE2/sse/blake2.h"
#else
#include "BLAKE2/neon/blake2.h"
#endif
#include "BLAKE3/blake3.h"
#include <memory>
#include <algorithm>
#include <string>
#include <list>
#include <map>
#include <vector>
#ifdef USE_STREEBOG
#include "Streebog.h"
#endif
#define DIRHASH_VERSION "1.26.1"
using namespace std;
typedef vector<unsigned char> ByteArray;
class CFilePtr;
static BYTE g_pbBuffer[4096];
static TCHAR g_szCanonalizedName[MAX_PATH + 1];
static WORD g_wAttributes = FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED;
static volatile WORD g_wCurrentAttributes;
static HANDLE g_hConsole = NULL;
static CONSOLE_SCREEN_BUFFER_INFO g_originalConsoleInfo;
static vector<shared_ptr<CFilePtr>> outputFiles;
static bool g_bLowerCase = false;
static bool g_bUseMsCrypto = false;
static bool g_bMismatchFound = false;
static bool g_bSkipError = false;
static bool g_bNoLogo = false;
static bool g_bNoFollow = false;
static HANDLE g_hThreads[256];
static WORD ThreadProcessorGroups[256] = { 0 };
static DWORD g_threadsCount = 0;
static volatile bool g_bStopThreads = false;
static volatile bool g_bFatalError = false;
static volatile bool g_bStopOutputThread = false;
static HANDLE g_hReadyEvent = NULL;
static HANDLE g_hStopEvent = NULL;
static HANDLE g_hOutputReadyEvent = NULL;
static HANDLE g_hOutputStopEvent = NULL;
static HANDLE g_hOutputThread = NULL;
static std::wstring g_szLastErrorMsg;
static wstring g_currentDirectory;
static bool g_sumFileSkipped = false;
static bool g_bSumRelativePath = false;
static bool g_bIncludeLastDir = false;
static wstring g_inputDirPath;
static size_t g_inputDirPathLength = 0;
static bool g_bLongPathNamesEnabled = false;
static list<wstring> onlySpecList;
static list<wstring> excludeSpecList;
typedef BOOL(WINAPI* SetThreadGroupAffinityFn)(
HANDLE hThread,
const GROUP_AFFINITY* GroupAffinity,
PGROUP_AFFINITY PreviousGroupAffinity
);
typedef WORD(WINAPI* GetActiveProcessorGroupCountFn)();
typedef DWORD(WINAPI* GetActiveProcessorCountFn)(
WORD GroupNumber
);
typedef HRESULT(WINAPI* PathAllocCanonicalizeFn)(
PCWSTR pszPathIn,
ULONG dwFlags,
PWSTR* ppszPathOut
);
typedef HRESULT(WINAPI *PathCchSkipRootFn)(
PCWSTR pszPath,
PCWSTR* ppszRootEnd
);
typedef HRESULT(WINAPI *PathAllocCombineFn)(
_In_opt_ PCWSTR pszPathIn,
_In_opt_ PCWSTR pszMore,
_In_ ULONG dwFlags,
_Outptr_ PWSTR* ppszPathOut
);
PathAllocCanonicalizeFn PathAllocCanonicalizePtr = NULL;
PathAllocCombineFn PathAllocCombinePtr = NULL;
PathCchSkipRootFn PathCchSkipRootPtr = NULL;
// Used for sorting directory content
bool compare_nocase(LPCWSTR first, LPCWSTR second)
{
return _wcsicmp(first, second) < 0;
}
TCHAR ToHex(unsigned char b)
{
if (b >= 0 && b <= 9)
return _T('0') + b;
else if (b >= 10 && b <= 15)
return (g_bLowerCase ? _T('a') : _T('A')) + b - 10;
else
return (g_bLowerCase ? _T('x') : _T('X'));
}
void ToHex(LPBYTE pbData, int iLen, LPTSTR szHex)
{
unsigned char b;
for (int i = 0; i < iLen; i++)
{
b = *pbData++;
*szHex++ = ToHex(b >> 4);
*szHex++ = ToHex(b & 0x0F);
}
*szHex = 0;
}
void ToHex (const ByteArray& data, LPTSTR szHex)
{
unsigned char b;
for (size_t i = 0; i < data.size(); i++)
{
b = data[i];
*szHex++ = ToHex(b >> 4);
*szHex++ = ToHex(b & 0x0F);
}
*szHex = 0;
}
bool FromHex(TCHAR c, unsigned char& b)
{
if (c >= _T('0') && c <= _T('9'))
b = c - _T('0');
else if (c >= _T('a') && c <= _T('f'))
b = 10 + (c - _T('a'));
else if (c >= _T('A') && c <= _T('F'))
b = 10 + (c - _T('A'));
else
return false;
return true;
}
bool FromHex(const TCHAR* szHex, ByteArray& buffer)
{
bool bRet = false;
buffer.clear();
if (szHex)
{
size_t l = _tcslen(szHex);
if (l % 2 == 0)
{
size_t i;
for (i = 0; i < l / 2; i++)
{
unsigned char b1, b2;
if (FromHex(*szHex++, b1) && FromHex(*szHex++, b2))
{
buffer.push_back(b1 * 16 + b2);
}
else
break;
}
if (i == (l / 2))
{
bRet = true;
}
else
buffer.clear();
}
}
return bRet;
}
std::wstring FormatString(LPCTSTR fmt, ...)
{
va_list args;
va_start(args, fmt);
int s = _vscwprintf(fmt, args);
va_end(args);
wchar_t* pStr = new wchar_t[s + 1];
va_start(args, fmt);
_vsnwprintf(pStr, (size_t) (s + 1), fmt, args);
va_end(args);
std::wstring ret = pStr;
delete[] pStr;
return ret;
}
void ShowMessage(WORD attributes, LPCTSTR szMsg, va_list args)
{
SetConsoleTextAttribute(g_hConsole, attributes);
_vtprintf(szMsg, args);
SetConsoleTextAttribute(g_hConsole, g_wCurrentAttributes);
}
void ShowMessageDirect(WORD attributes, LPCTSTR szMsg)
{
SetConsoleTextAttribute(g_hConsole, attributes);
_tprintf(L"%s", szMsg);
SetConsoleTextAttribute(g_hConsole, g_wCurrentAttributes);
}
void ShowError(LPCTSTR szMsg, ...)
{
va_list args;
va_start(args, szMsg);
ShowMessage (FOREGROUND_RED | FOREGROUND_INTENSITY, szMsg, args);
va_end(args);
}
void ShowErrorDirect(LPCTSTR szMsg)
{
ShowMessageDirect (FOREGROUND_RED | FOREGROUND_INTENSITY, szMsg);
}
void ShowWarning(LPCTSTR szMsg, ...)
{
va_list args;
va_start(args, szMsg);
ShowMessage(FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_INTENSITY, szMsg, args);
va_end(args);
}
void ShowWarningDirect(LPCTSTR szMsg)
{
ShowMessageDirect(FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_INTENSITY, szMsg);
}
typedef NTSTATUS(WINAPI* RtlGetVersionFn)(
PRTL_OSVERSIONINFOW lpVersionInformation);
BOOL GetWindowsVersion(OSVERSIONINFOW* pOSversion)
{
BOOL bRet = FALSE;
HMODULE h = LoadLibrary(TEXT("ntdll.dll"));
if (h != NULL)
{
RtlGetVersionFn pRtlGetVersion = (RtlGetVersionFn)GetProcAddress(h, "RtlGetVersion");
if (pRtlGetVersion != NULL)
{
if (NO_ERROR == pRtlGetVersion((PRTL_OSVERSIONINFOW)pOSversion))
bRet = TRUE;
}
FreeLibrary(h);
}
return bRet;
}
LPCWSTR GetFileName(LPCWSTR szPath)
{
size_t len = wcslen(szPath);
LPCWSTR ptr;
if (len <= 1)
return szPath;
ptr = szPath + (len - 1);
if (*ptr == L'\\' || *ptr == L'/')
ptr--;
while (ptr != szPath)
{
if (*ptr == L'\\' || *ptr == L'/')
break;
ptr--;
}
if (*ptr == L'\\' || *ptr == L'/')
return ptr + 1;
else
return ptr;
}
bool IsDriveLetter(WCHAR c)
{
return ((c >= L'A' && c <= L'Z') || (c >= L'a' && c <= L'z'));
}
bool IsAbsolutPath(LPCWSTR szPath)
{
bool bRet = false;
size_t pathLen = wcslen(szPath);
if (pathLen > MAX_PATH)
{
if (PathCchSkipRootPtr)
{
LPCWSTR ptr = NULL;
HRESULT hr = PathCchSkipRootPtr(szPath, &ptr);
if (S_OK == hr)
bRet = true;
}
else
{
// do the check manually by looking for drive letter or "\\serverName\" prefix
if (pathLen >= 4 && szPath[1] == L':' && szPath[2] == L'\\' && IsDriveLetter(szPath[0]))
bRet = true;
else if (pathLen >= 5 && szPath[0] == L'\\' && szPath[1] == L'\\')
{
for (size_t i = 2; i < (pathLen - 1); i++)
{
if (szPath[i] == L'\\')
{
bRet = true;
break;
}
}
}
}
}
else
{
if (!PathIsRelativeW(szPath))
bRet = true;
}
return bRet;
}
wstring EnsureAbsolut(LPCWSTR szPath)
{
wstring strVal = szPath;
size_t pathLen = wcslen(szPath);
if (pathLen)
{
WCHAR g_szCanonalizedName[MAX_PATH + 1];
if (IsAbsolutPath(strVal.c_str()))
{
if (pathLen > MAX_PATH)
{
if (PathAllocCanonicalizePtr)
{
LPWSTR pCanonicalName = NULL;
if (S_OK == PathAllocCanonicalizePtr(strVal.c_str(), PATHCCH_ALLOW_LONG_PATHS, &pCanonicalName))
strVal = pCanonicalName;
if (pCanonicalName)
LocalFree(pCanonicalName);
}
}
else
{
if (PathCanonicalizeW(g_szCanonalizedName, strVal.c_str()))
strVal = g_szCanonalizedName;
}
}
else
{
bool bDone = false;
LPCWSTR szParent = g_currentDirectory.c_str();
if (PathAllocCombinePtr)
{
LPWSTR szCombined = NULL;
HRESULT hr = PathAllocCombinePtr(szParent, strVal.c_str(), PATHCCH_ALLOW_LONG_PATHS, &szCombined);
if (S_OK == hr)
{
strVal = szCombined;
bDone = true;
}
if (szCombined)
LocalFree(szCombined);
}
if (!bDone && ((wcslen(szParent) + pathLen) < MAX_PATH))
{
if (PathCombineW(g_szCanonalizedName, szParent, strVal.c_str()))
{
strVal = g_szCanonalizedName;
bDone = true;
}
}
if (!bDone)
{
if ((pathLen >= 2) && strVal[0] == L'\\' && strVal[1] != L'\\')
{
// use drive letter of current directory
WCHAR szDrv[3] = { szParent[0], szParent[1], 0 };
strVal = szDrv + strVal;
}
else
strVal = szParent + strVal;
}
}
if (!g_bLongPathNamesEnabled)
{
// on old Windows versions, use \\?\ prefix to increase the path limit to 32767 characters
std::wstring res = L"\\\\?\\";
//detect UNC
if (strVal[0] == L'\\' && strVal[1] == L'\\')
{
res += L"UNC\\";
strVal = res + (strVal.c_str() + 2);
}
else
strVal = res + strVal;
}
}
return strVal;
}
/* code to detect Symbolic Links, Junction Points and Mount Points from
* http://blog.kalmbach-software.de/2008/02/
*
*
*/
typedef struct _REPARSE_DATA_BUFFER {
ULONG ReparseTag;
USHORT ReparseDataLength;
USHORT Reserved;
union {
struct {
USHORT SubstituteNameOffset;
USHORT SubstituteNameLength;
USHORT PrintNameOffset;
USHORT PrintNameLength;
ULONG Flags; // it seems that the docu is missing this entry (at least 2008-03-07)
WCHAR PathBuffer[1];
} SymbolicLinkReparseBuffer;
struct {
USHORT SubstituteNameOffset;
USHORT SubstituteNameLength;
USHORT PrintNameOffset;
USHORT PrintNameLength;
WCHAR PathBuffer[1];
} MountPointReparseBuffer;
struct {
UCHAR DataBuffer[1];
} GenericReparseBuffer;
};
} REPARSE_DATA_BUFFER, * PREPARSE_DATA_BUFFER;
bool IsReparsePoint(LPCTSTR szPath)
{
bool bRet = false;
HANDLE hFile;
hFile = CreateFile(szPath, FILE_READ_EA, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT, NULL);
if (hFile != INVALID_HANDLE_VALUE)
{
// Allocate the reparse data structure
DWORD dwBufSize = MAXIMUM_REPARSE_DATA_BUFFER_SIZE;
REPARSE_DATA_BUFFER* rdata = (REPARSE_DATA_BUFFER*) new BYTE[dwBufSize];
// Query the reparse data
DWORD dwRetLen;
if (DeviceIoControl(hFile, FSCTL_GET_REPARSE_POINT, NULL, 0, rdata, dwBufSize, &dwRetLen, NULL))
{
if (IsReparseTagMicrosoft(rdata->ReparseTag))
{
if (rdata->ReparseTag == IO_REPARSE_TAG_SYMLINK)
{
bRet = true;
}
else if (rdata->ReparseTag == IO_REPARSE_TAG_MOUNT_POINT) // this applies also for Junction Point
{
bRet = true;
}
}
}
CloseHandle(hFile);
delete[](BYTE*) rdata;
}
return bRet;
}
class CPath
{
protected:
std::wstring m_path;
std::wstring m_absolutPath;
public:
CPath()
{
}
explicit CPath(LPCWSTR szPath) : m_path(szPath)
{
std::replace(m_path.begin(), m_path.end(), L'/', L'\\');
m_absolutPath = EnsureAbsolut(m_path.c_str());
}
CPath(LPCWSTR szPath, LPCWSTR szAbsolutPath) : m_path(szPath), m_absolutPath(szPath)
{
}
CPath(const CPath& path) : m_path(path.m_path), m_absolutPath(path.m_absolutPath)
{
}
CPath& operator = (const CPath& p)
{
m_path = p.m_path;
m_absolutPath = p.m_absolutPath;
return *this;
}
CPath& operator = (LPCWSTR p)
{
m_path = p;
std::replace(m_path.begin(), m_path.end(), L'/', L'\\');
m_absolutPath = EnsureAbsolut(m_path.c_str());
return *this;
}
void AppendName(LPCWSTR szName)
{
m_path += L"\\";
m_path += szName;
m_absolutPath += L"\\";
m_absolutPath += szName;
}
const std::wstring& GetPathValue() const { return m_path; }
const std::wstring& GetAbsolutPathValue() const { return m_absolutPath; }
};
// ---------------------------------------------
// class to hold FILE pointers and close them automatically
// it provides a cast operator to FILE*
class CFilePtr
{
protected:
FILE* m_pFile;
FILE* m_pShadowFile;
wstring m_fileName;
wstring m_shadowFileName;
// forbid copying
CFilePtr(const CFilePtr&) : m_pFile(NULL), m_pShadowFile(NULL), m_fileName(L""), m_shadowFileName(L"")
{
}
CFilePtr& operator = (const CFilePtr&)
{
return *this;
}
public:
CFilePtr() : m_pFile(NULL), m_pShadowFile(NULL)
{
}
explicit CFilePtr(FILE* pFile, const wstring& name, FILE* pShadowFile, const wstring& shadowName)
: m_pFile(pFile), m_pShadowFile(pShadowFile), m_fileName(name), m_shadowFileName(shadowName)
{
}
~CFilePtr()
{
Close();
}
const wstring& GetFileName() const { return m_fileName; }
const wstring& GetShadowFileName() const { return m_shadowFileName; }
FILE* GetShadowFile() const { return m_pShadowFile; }
operator FILE* () const { return m_pFile; }
FILE* operator -> () const { return m_pFile; }
void CloseShadowFile()
{
if (m_pShadowFile)
{
fclose(m_pShadowFile);
m_pShadowFile = NULL;
}
}
void Close()
{
if (m_pFile)
{
fclose(m_pFile);
m_pFile = NULL;
}
if (m_pShadowFile)
{
fclose(m_pShadowFile);
m_pShadowFile = NULL;
}
}
};
// ---------------------------------------------
/*
* This class is used to make Windows console where we are ruuning compatible with printing UNICODE characters
* Note that in order to display UNICODE characters correctly, the console should be using a font that support
* this UNICODE characters. "Courier New" font is a good choice.
*/
class CConsoleUnicodeOutputInitializer
{
protected:
UINT m_originalCP;
public:
CConsoleUnicodeOutputInitializer()
{
m_originalCP = GetConsoleOutputCP();
SetConsoleOutputCP(CP_UTF8);
_setmode(_fileno(stdout), _O_U8TEXT);
}
~CConsoleUnicodeOutputInitializer()
{
SetConsoleOutputCP(m_originalCP);
}
};
// ---------------------------------------------
class Hash
{
public:
virtual void Init() = 0;
virtual void Update(LPCBYTE pbData, size_t dwLength) = 0;
virtual void Final(LPBYTE pbDigest) = 0;
virtual int GetHashSize() = 0;
virtual LPCTSTR GetID() = 0;
virtual bool IsValid() const { return true; }
virtual bool UsesMSCrypto() const { return false; }
virtual Hash* Clone() { return GetHash(GetID()); }
static bool IsHashId(LPCTSTR szHashId);
static bool IsHashSize(int size);
static Hash* GetHash(LPCTSTR szHashId);
static std::vector<std::wstring> GetSupportedHashIds();
static bool IsHashIdCombination(LPCTSTR szHashId);
static std::vector<std::shared_ptr<Hash>> GetHashes(LPCTSTR szHashId);
void* operator new(size_t i)
{
return _mm_malloc(i, 16);
}
void operator delete(void* p)
{
_mm_free(p);
}
};
class NeonBlake2s : public Hash
{
protected:
blake2s_state m_ctx;
public:
NeonBlake2s() : Hash()
{
Init();
}
void Init() { blake2s_init(&m_ctx, BLAKE2S_OUTBYTES); }
void Update(LPCBYTE pbData, size_t dwLength) { blake2s_update(&m_ctx, pbData, dwLength); }
void Final(LPBYTE pbDigest) { blake2s_final(&m_ctx, pbDigest, BLAKE2S_OUTBYTES); }
LPCTSTR GetID() { return _T("Blake2s"); }
int GetHashSize() { return BLAKE2S_OUTBYTES; }
};
class NeonBlake2b : public Hash
{
protected:
blake2b_state m_ctx;
public:
NeonBlake2b() : Hash()
{
Init();
}
void Init() { blake2b_init(&m_ctx, BLAKE2B_OUTBYTES); }
void Update(LPCBYTE pbData, size_t dwLength) { blake2b_update(&m_ctx, pbData, dwLength); }
void Final(LPBYTE pbDigest) { blake2b_final(&m_ctx, pbDigest, BLAKE2B_OUTBYTES); }
LPCTSTR GetID() { return _T("Blake2b"); }
int GetHashSize() { return BLAKE2B_OUTBYTES; }
};
#ifdef USE_STREEBOG
class Streebog : public Hash
{
protected:
STREEBOG_CTX m_ctx;
public:
Streebog() : Hash()
{
STREEBOG_init(&m_ctx);
}
void Init() { STREEBOG_init(&m_ctx); }
void Update(LPCBYTE pbData, size_t dwLength) { STREEBOG_add(&m_ctx, pbData, dwLength); }
void Final(LPBYTE pbDigest) { STREEBOG_finalize(&m_ctx, pbDigest); }
LPCTSTR GetID() { return _T("Streebog"); }
int GetHashSize() { return 64; }
};
#endif
class CngHash : public Hash
{
protected:
BCRYPT_ALG_HANDLE m_hAlg;
BCRYPT_HASH_HANDLE m_hash;
LPWSTR m_wszAlg;
ULONG m_cbHashObject;
unsigned char* m_pbHashObject;
public:
CngHash(LPCWSTR wszAlg) : Hash(), m_hAlg(NULL), m_hash(NULL), m_wszAlg(NULL), m_pbHashObject(NULL), m_cbHashObject(0)
{
m_wszAlg = _wcsdup(wszAlg);
Init();
}
virtual ~CngHash()
{
Clear();
if (m_wszAlg)
free(m_wszAlg);
}
void Clear()
{
if (m_hash)
BCryptDestroyHash(m_hash);
if (m_hAlg)
BCryptCloseAlgorithmProvider(m_hAlg, 0);
if (m_pbHashObject)
delete[] m_pbHashObject;
m_pbHashObject = NULL;
m_cbHashObject = 0;
m_hash = NULL;
m_hAlg = NULL;
}
virtual bool IsValid() const { return (m_hash != NULL); }
virtual bool UsesMSCrypto() const { return true; }
virtual void Init() {
Clear();
if (STATUS_SUCCESS == BCryptOpenAlgorithmProvider(&m_hAlg, m_wszAlg, MS_PRIMITIVE_PROVIDER, 0))
{
DWORD dwValue, count = sizeof(DWORD);
if (STATUS_SUCCESS == BCryptGetProperty(m_hAlg, BCRYPT_OBJECT_LENGTH, (PUCHAR)&dwValue, count, &count, 0))
{
m_cbHashObject = dwValue;
m_pbHashObject = new unsigned char[dwValue];
if (STATUS_SUCCESS != BCryptCreateHash(m_hAlg, &m_hash, m_pbHashObject, m_cbHashObject, NULL, 0, 0))
{
m_cbHashObject = 0;
delete[] m_pbHashObject;
m_pbHashObject = NULL;
}
}
}
if (!m_pbHashObject)
{
Clear();
}
}
virtual void Update(LPCBYTE pbData, size_t dwLength) {
if (IsValid())
{
BCryptHashData(m_hash, (PUCHAR)pbData, (ULONG)dwLength, 0);
}
}
virtual void Final(LPBYTE pbDigest) {
if (IsValid())
{
ULONG dwHashLen = (ULONG)GetHashSize();
BCryptFinishHash(m_hash, pbDigest, dwHashLen, 0);
}
}
};
class Md5Cng : public CngHash
{
public:
Md5Cng() : CngHash(BCRYPT_MD5_ALGORITHM)
{
}
~Md5Cng()
{
}
LPCTSTR GetID() { return _T("MD5"); }
int GetHashSize() { return 16; }
};
class Sha1Cng : public CngHash
{
public:
Sha1Cng() : CngHash(BCRYPT_SHA1_ALGORITHM)
{
}
~Sha1Cng()
{
}
LPCTSTR GetID() { return _T("SHA1"); }
int GetHashSize() { return 20; }
};
class Sha256Cng : public CngHash
{
public:
Sha256Cng() : CngHash(BCRYPT_SHA256_ALGORITHM)
{
}
~Sha256Cng()
{
}
LPCTSTR GetID() { return _T("SHA256"); }
int GetHashSize() { return 32; }
};
class Sha384Cng : public CngHash
{
public:
Sha384Cng() : CngHash(BCRYPT_SHA384_ALGORITHM)
{
}
~Sha384Cng()
{
}
LPCTSTR GetID() { return _T("SHA384"); }
int GetHashSize() { return 48; }
};
class Sha512Cng : public CngHash
{
public:
Sha512Cng() : CngHash(BCRYPT_SHA512_ALGORITHM)
{
}
~Sha512Cng()
{
}
LPCTSTR GetID() { return _T("SHA512"); }
int GetHashSize() { return 64; }
};
class Blake3Hash : public Hash
{
protected:
blake3_hasher m_ctx;
public:
Blake3Hash() : Hash()
{
Init();
}
void Init() { blake3_hasher_init(&m_ctx); }
void Update(LPCBYTE pbData, size_t dwLength) { blake3_hasher_update(&m_ctx, pbData, dwLength); }
void Final(LPBYTE pbDigest) { blake3_hasher_finalize(&m_ctx, pbDigest, BLAKE3_OUT_LEN); }
LPCTSTR GetID() { return _T("Blake3"); }
int GetHashSize() { return BLAKE3_OUT_LEN; }
};
bool Hash::IsHashId(LPCTSTR szHashId)
{
if ((_tcsicmp(szHashId, _T("SHA1")) == 0)
|| (_tcsicmp(szHashId, _T("SHA256")) == 0)
|| (_tcsicmp(szHashId, _T("SHA384")) == 0)
|| (_tcsicmp(szHashId, _T("SHA512")) == 0)
|| (_tcsicmp(szHashId, _T("MD5")) == 0)
|| (_tcsicmp(szHashId, _T("Streebog")) == 0)
|| (_tcsicmp(szHashId, _T("Blake2s")) == 0)
|| (_tcsicmp(szHashId, _T("Blake2b")) == 0)
|| (_tcsicmp(szHashId, _T("Blake3")) == 0)
)
{
return true;
}
else
return false;
}
// Check if a given string is a single hash id or combination of several hash ids separated by a comma character
// for example: "SHA512" or "SHA1,MD5" or "SHA256,Blake2s,Blake3"
// it uses the IsHashId method to check if each part of the string is a valid hash id
// if the string is a combination of hash ids, it returns true, otherwise it returns false
bool Hash::IsHashIdCombination(LPCTSTR szHashId)
{
if (!szHashId)
return false;
std::wstring strHashId(szHashId);
std::wstring strHashIdPart;
std::wstring::size_type pos = 0;