1
0
This repository has been archived on 2025-07-27. You can view files and clone it, but cannot push or open issues or pull requests.
Files
siadrive/SiaDrive.Api/SiaCommon.cpp
2017-02-26 23:32:14 -06:00

87 lines
2.2 KiB
C++

#include "stdafx.h"
#include "SiaCommon.h"
#include <ttmath/ttmath.h>
#include <Wincrypt.h>
NS_BEGIN(Sia)
NS_BEGIN(Api)
String AFX_EXT_API GenerateSha256(const String& str)
{
String ret;
HCRYPTPROV hCryptProv = 0;
HCRYPTHASH hHash = 0;
BOOL ok = CryptAcquireContext(&hCryptProv, NULL, NULL, PROV_RSA_AES, 0);
ok = ok && CryptCreateHash(hCryptProv, CALG_SHA_256, 0, 0, &hHash);
ok = ok && CryptHashData(hHash, reinterpret_cast<const BYTE*>(&str[0]), str.length() * sizeof(TCHAR), 0);
if (ok)
{
DWORD dwHashLen;
DWORD dwCount = sizeof(DWORD);
if (CryptGetHashParam(hHash, HP_HASHSIZE, reinterpret_cast<BYTE *>(&dwHashLen), &dwCount, 0))
{
std::vector<unsigned char> hash(dwHashLen);
if (CryptGetHashParam(hHash, HP_HASHVAL, reinterpret_cast<BYTE *>(&hash[0]), &dwHashLen, 0))
{
std::ostringstream ss;
ss << std::hex << std::uppercase << std::setfill('0');
for (int c : hash)
{
ss << std::setw(2) << c;
}
std::string s = ss.str();
ret = CA2W(s.c_str()).m_psz;
}
}
}
if (hHash) CryptDestroyHash(hHash);
if (hCryptProv) CryptReleaseContext(hCryptProv, 0);
return ret;
}
BOOL RecurDeleteFilesByExtentsion(const String& folder, const String& extensionWithDot)
{
BOOL ret = FALSE;
WIN32_FIND_DATA fd = { 0 };
String search;
search.resize(MAX_PATH + 1);
::PathCombine(&search[0], folder.c_str(), L"*.*");
HANDLE find = FindFirstFile(search.c_str(), &fd);
if (find != INVALID_HANDLE_VALUE)
{
ret = TRUE;
do
{
if (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
{
if ((_tcscmp(fd.cFileName, L".") != 0) && (_tcscmp(fd.cFileName, L"..") != 0))
{
String nextFolder;
nextFolder.resize(MAX_PATH + 1);
::PathCombine(&nextFolder[0], folder.c_str(), fd.cFileName);
ret = RecurDeleteFilesByExtentsion(nextFolder, extensionWithDot);
}
}
else
{
String ext = ::PathFindExtension(fd.cFileName);
if (_tcscmp(ext.c_str(), extensionWithDot.c_str()) == 0)
{
String filePath;
filePath.resize(MAX_PATH + 1);
::PathCombine(&filePath[0], folder.c_str(), fd.cFileName);
ret = RetryDeleteFileIfExists(filePath.c_str());
}
}
} while (ret && (FindNextFile(find, &fd) != 0));
}
return ret;
}
NS_END(2)