|
1 | 1 | #include "common.h" |
2 | 2 |
|
| 3 | +#include <wincrypt.h> |
| 4 | + |
| 5 | +#include <stdexcept> |
| 6 | + |
| 7 | +#include <openssl/ssl.h> |
| 8 | + |
| 9 | +#include <spdlog/spdlog.h> |
| 10 | + |
3 | 11 | namespace hcpp |
4 | 12 | { |
5 | | - void set_platform_default_verify_store(ssl::context& ctx) |
| 13 | + namespace log = spdlog; |
| 14 | + |
| 15 | + //https://stackoverflow.com/questions/9507184/can-openssl-on-windows-use-the-system-certificate-store?rq=3 |
| 16 | + //https://www.coder.work/article/1710481 |
| 17 | + struct cert_store |
6 | 18 | { |
| 19 | + X509_STORE *store_ = nullptr; |
| 20 | + cert_store() |
| 21 | + { |
| 22 | + log::error("cert_store构造函数"); |
| 23 | + try |
| 24 | + { |
| 25 | + auto hCertStore = CertOpenSystemStore(0, "ROOT"); |
| 26 | + if (!hCertStore) |
| 27 | + { |
| 28 | + throw std::runtime_error("CertOpenSystemStore 失败"); |
| 29 | + } |
| 30 | + store_ = X509_STORE_new(); |
7 | 31 |
|
| 32 | + PCCERT_CONTEXT pCertContext = nullptr; |
| 33 | + while (true) |
| 34 | + { |
| 35 | + pCertContext = CertEnumCertificatesInStore(hCertStore, pCertContext); |
| 36 | + if (pCertContext == nullptr) |
| 37 | + { |
| 38 | + break; |
| 39 | + } |
| 40 | + // https://www.openssl.org/docs/manmaster/man3/d2i_X509.html |
| 41 | + X509 *cert = d2i_X509(nullptr, (const unsigned char **)&pCertContext->pbCertEncoded, pCertContext->cbCertEncoded); |
| 42 | + if (cert == nullptr) |
| 43 | + { |
| 44 | + throw std::runtime_error("d2i_X509 获取证书失败"); |
| 45 | + } |
| 46 | + X509_STORE_add_cert(store_, cert); |
| 47 | + X509_free(cert); |
| 48 | + } |
| 49 | + if (CertFreeCertificateContext(pCertContext) == 0) |
| 50 | + { |
| 51 | + throw std::runtime_error("CertFreeCertificateContext 释放pCertContext失败"); |
| 52 | + } |
| 53 | + if (!CertCloseStore(hCertStore, 0)) |
| 54 | + { |
| 55 | + throw std::runtime_error("CertCloseStore 失败"); |
| 56 | + } |
| 57 | + } |
| 58 | + catch (...) |
| 59 | + { |
| 60 | + X509_STORE_free(store_); |
| 61 | + throw; |
| 62 | + } |
| 63 | + } |
| 64 | + ~cert_store() |
| 65 | + { |
| 66 | + //BUG 为什么不调用 还要保没有其它人拥有此store_ |
| 67 | + log::error("cert_store析构函数"); |
| 68 | + X509_STORE_free(store_); |
| 69 | + } |
| 70 | + }; |
| 71 | + // https://www.coder.work/article/1710481 |
| 72 | + // https://learn.microsoft.com/zh-cn/windows/win32/api/wincrypt/nf-wincrypt-certopensystemstorea |
| 73 | + void set_platform_default_verify_store(ssl::context &ctx) |
| 74 | + { |
| 75 | + static cert_store cs{}; |
| 76 | + SSL_CTX_set1_cert_store(ctx.native_handle(), cs.store_); |
8 | 77 | } |
9 | 78 | } // namespace hcpp |
0 commit comments