Created
February 9, 2023 22:54
-
-
Save eecsmap/1ddf2a14479d83eefc2716db068a205f to your computer and use it in GitHub Desktop.
add_root_cert
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <Windows.h> | |
#include <WinCrypt.h> | |
#include <iostream> | |
#pragma comment (lib, "Crypt32.lib") | |
bool InstallCertificate(const char* certificateFile, const char* certificateStore) | |
{ | |
bool success = false; | |
HCERTSTORE hCertStore = CertOpenStore(CERT_STORE_PROV_SYSTEM, 0, NULL, CERT_SYSTEM_STORE_CURRENT_USER | CERT_STORE_READONLY_FLAG, certificateStore); | |
if (hCertStore != NULL) | |
{ | |
PCCERT_CONTEXT pCertContext = CertCreateCertificateContext(X509_ASN_ENCODING, NULL, 0); | |
if (pCertContext != NULL) | |
{ | |
DWORD dwCertEncoding = X509_ASN_ENCODING | PKCS_7_ASN_ENCODING; | |
DWORD dwContentType = 0; | |
DWORD dwFormatType = 0; | |
const void* pvCertStore = NULL; | |
HCERTSTORE hCertStoreTemp = NULL; | |
if (CryptQueryObject(CERT_QUERY_OBJECT_FILE, certificateFile, CERT_QUERY_CONTENT_FLAG_ALL, CERT_QUERY_FORMAT_FLAG_ALL, 0, &dwContentType, &dwFormatType, &hCertStoreTemp, &pvCertStore, NULL)) | |
{ | |
if (CertAddCertificateContextToStore(hCertStore, pCertContext, CERT_STORE_ADD_USE_EXISTING, NULL)) | |
{ | |
std::cout << "The certificate was successfully installed in the " << certificateStore << " store." << std::endl; | |
success = true; | |
} | |
else | |
{ | |
std::cout << "Failed to add the certificate to the " << certificateStore << " store. Error code: " << GetLastError() << std::endl; | |
} | |
CertCloseStore(hCertStoreTemp, 0); | |
} | |
else | |
{ | |
std::cout << "Failed to query the certificate object. Error code: " << GetLastError() << std::endl; | |
} | |
CertFreeCertificateContext(pCertContext); | |
} | |
else | |
{ | |
std::cout << "Failed to create the certificate context. Error code: " << GetLastError() << std::endl; | |
} | |
CertCloseStore(hCertStore, 0); | |
} | |
else | |
{ | |
std::cout << "Failed to open the " << certificateStore << " store. Error code: " << GetLastError() << std::endl; | |
} | |
return success; | |
} | |
int main(int argc, char* argv[]) | |
{ | |
if (argc == 3) | |
{ | |
const char* certificateFile = argv[1]; | |
const char* certificateStore = argv[2]; | |
if (!InstallCertificate(certificateFile, certificateStore)) | |
{ | |
std::cout << "Installation failed." << std::endl; | |
return 1 | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment