std::unique_ptr<wchar_t[]> CStringUtils::Decrypt(const wchar_t * text) { DWORD dwLen = 0; if (CryptStringToBinaryW(text, (DWORD)wcslen(text), CRYPT_STRING_HEX, NULL, &dwLen, NULL, NULL) == FALSE) return NULL; std::unique_ptr<BYTE[]> strIn(new BYTE[dwLen + 1]); if (CryptStringToBinaryW(text, (DWORD)wcslen(text), CRYPT_STRING_HEX, strIn.get(), &dwLen, NULL, NULL) == FALSE) return NULL; DATA_BLOB blobin; blobin.cbData = dwLen; blobin.pbData = strIn.get(); LPWSTR descr = nullptr; DATA_BLOB blobout = { 0 }; if (CryptUnprotectData(&blobin, &descr, NULL, NULL, NULL, CRYPTPROTECT_UI_FORBIDDEN, &blobout) == FALSE) return NULL; SecureZeroMemory(blobin.pbData, blobin.cbData); std::unique_ptr<wchar_t[]> result(new wchar_t[(blobout.cbData) / sizeof(wchar_t) + 1]); wcsncpy_s(result.get(), (blobout.cbData) / sizeof(wchar_t) + 1, (const wchar_t*)blobout.pbData, blobout.cbData / sizeof(wchar_t)); SecureZeroMemory(blobout.pbData, blobout.cbData); LocalFree(blobout.pbData); LocalFree(descr); return result; }
HRESULT DeserializePropVariantFromString(PCWSTR pszIn, PROPVARIANT *ppropvar) { HRESULT hr = E_FAIL; DWORD dwFormatUsed, dwSkip, cbBlob; // compute and validate the required buffer size if (CryptStringToBinaryW(pszIn, 0, CRYPT_STRING_BASE64, NULL, &cbBlob, &dwSkip, &dwFormatUsed) && dwSkip == 0 && dwFormatUsed == CRYPT_STRING_BASE64) { // allocate a buffer to hold the serialized binary blob hr = E_OUTOFMEMORY; BYTE *pbSerialized = (BYTE *)CoTaskMemAlloc(cbBlob); if (pbSerialized) { // convert the string to a serialized binary blob hr = E_FAIL; if (CryptStringToBinaryW(pszIn, 0, CRYPT_STRING_BASE64, pbSerialized, &cbBlob, &dwSkip, &dwFormatUsed)) { // deserialized the blob back into a PROPVARIANT value hr = StgDeserializePropVariant((SERIALIZEDPROPERTYVALUE *)pbSerialized, cbBlob, ppropvar); } CoTaskMemFree(pbSerialized); } } return hr; }
int FromBase64Crypto( const BYTE* pSrc, int nLenSrc, wchar_t* pDst, int nLenDst ) { DWORD nLenOut= nLenDst; BOOL fRet= CryptStringToBinaryW((LPCWSTR)pSrc, nLenSrc,CRYPT_STRING_BASE64,(BYTE*)pDst, &nLenOut,NULL,NULL); if (!fRet) nLenOut=0; return( nLenOut ); }