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-22 19:25:04 -06:00

44 lines
1.1 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;
}
NS_END(2)