Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #define WIN32_LEAN_AND_MEAN
- #include <Windows.h>
- #include <wincrypt.h>
- #include <iostream>
- #include <fstream>
- #include <string>
- #include <vector>
- #pragma comment (lib, "Crypt32.lib")
- extern "C" HRESULT CertInstallSingleCertificate(
- __in HCERTSTORE hStore,
- __in PCCERT_CONTEXT pCertContext,
- __in LPCWSTR wzName
- )
- {
- CERT_BLOB blob = { };
- blob.pbData = (BYTE*)wzName;
- blob.cbData = (lstrlenW(wzName) + 1) * sizeof(WCHAR); // including terminating null
- if (!::CertSetCertificateContextProperty(pCertContext, CERT_FRIENDLY_NAME_PROP_ID, 0, &blob))
- {
- std::cout << "Failed to set the friendly name of the certificate\n";
- return STATUS_FATAL_APP_EXIT;
- }
- /*
- CERT_STORE_ADD_REPLACE_EXISTING will not work if the certificate exists
- in the Group Policy or Enterprise certificate stores.
- CERT_STORE_ADD_USE_EXISTING is what mmc.exe + certificate snapin uses.
- This works fine (because it never actually needs to add)
- */
- if (!::CertAddCertificateContextToStore(hStore, pCertContext, CERT_STORE_ADD_REPLACE_EXISTING, NULL))
- {
- std::cout << "Failed to add certificate to the store.\n";
- }
- else
- {
- std::cout << "Certificate added to certificate store. \n";
- }
- }
- static void InstallCertificatePackage(
- __in HCERTSTORE hStore,
- __in LPCWSTR wzName,
- __in_opt BYTE* rgbData,
- __in DWORD cbData
- )
- {
- CERT_BLOB blob = { 0 };
- blob.pbData = rgbData;
- blob.cbData = cbData;
- PCCERT_CONTEXT pCertContext = NULL;
- DWORD dwEncodingType = 0;
- DWORD dwContentType = 0;
- DWORD dwFormatType = 0;
- if (!::CryptQueryObject(CERT_QUERY_OBJECT_BLOB, &blob, CERT_QUERY_CONTENT_FLAG_ALL, CERT_QUERY_FORMAT_FLAG_ALL, 0, &dwEncodingType, &dwContentType, &dwFormatType, NULL, NULL, (LPCVOID*)&pCertContext))
- {
- std::cout << "Failed to parse the certificate blob\n";
- return;
- }
- int iUniqueId = 0;
- std::wstring uniqueName = std::wstring(wzName) + L"_wixCert_" + std::to_wstring(++iUniqueId);
- CertInstallSingleCertificate(hStore, pCertContext, uniqueName.c_str());
- ::CertFreeCertificateContext(pCertContext);
- }
- int main()
- {
- std::ifstream file("C:\\Users\\jst\\Desktop\\<YOUR_CA_CERT>", std::ios::binary | std::ios::ate);
- std::streamsize size = file.tellg();
- if (size != -1)
- {
- file.seekg(0, std::ios::beg);
- std::vector<char> buffer(size);
- file.read(buffer.data(), size);
- std::wstring storeName = L"root";
- auto hCertStore = ::CertOpenStore(CERT_STORE_PROV_SYSTEM, 0, NULL, CERT_SYSTEM_STORE_LOCAL_MACHINE, storeName.c_str());
- if (hCertStore)
- {
- InstallCertificatePackage(hCertStore, L"My Root CA", (BYTE*)buffer.data(), size);
- CertCloseStore(hCertStore, 0);
- }
- else
- {
- std::cout << "Unable to open certificate store\n";
- }
- }
- else
- {
- std::cout << "Unable to read file\n";
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement