Created
September 17, 2024 13:20
-
-
Save luncliff/a2be7668da6ce870810d1804fedbba86 to your computer and use it in GitHub Desktop.
Windows Certificates to OpenSSL X509_STORE
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
/// @see https://stackoverflow.com/a/40046425 | |
#include <memory> | |
#include <WinSock2.h> | |
#include <Windows.h> | |
#include <cryptuiapi.h> | |
#include <wincrypt.h> | |
/** | |
* @see https://docs.microsoft.com/en-us/windows/win32/api/wincrypt/nf-wincrypt-certopensystemstorew | |
* @see https://docs.microsoft.com/en-us/windows/win32/api/wincrypt/nf-wincrypt-certenumcertificatesinstore | |
* | |
* @code | |
* #include <openssl/ssl.h> | |
* | |
* uint32_t load_system_certificates(SSL_CTX* ssl) noexcept { | |
* X509_STORE* store = SSL_CTX_get_cert_store(ssl); | |
* return load_system_certificates(store); | |
* } | |
* @endcode | |
*/ | |
uint32_t load_system_certificates(X509_STORE* store) noexcept { | |
HCERTSTORE certs = CertOpenSystemStoreW(0, L"CA"); | |
if (certs == nullptr) | |
return GetLastError(); | |
PCCERT_CONTEXT context = CertEnumCertificatesInStore(certs, nullptr); | |
for (; context; context = CertEnumCertificatesInStore(certs, context)) { | |
const auto* cert = reinterpret_cast<unsigned char*>(context->pbCertEncoded); | |
const auto certlen = context->cbCertEncoded; | |
auto x509 = std::unique_ptr<X509, void (*)(X509*)>{d2i_X509(nullptr, &cert, certlen), &X509_free}; | |
if (x509 == nullptr) | |
continue; | |
X509_STORE_add_cert(store, x509.get()); | |
} | |
if (context) | |
CertFreeCertificateContext(context); | |
return CertCloseStore(certs, 0) == FALSE ? GetLastError() : S_OK; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment