Commit 7bd38a3eb34b8248dd48a541feb4ff245acf0bb0

Authored by Jay Berkenbilt
1 parent 6c39aa87

Provide error message in Windows crypto code (fixes #286)

Thanks to github user zdenop for supplying some additional
error-handling code.
ChangeLog
1 1 2019-06-22 Jay Berkenbilt <ejb@ql.org>
2 2  
  3 + * Provided a more useful error message when Windows can't get
  4 + security context. Thanks to user zdenop for supplying some code.
  5 + Fixes #286.
  6 +
3 7 * Favor PointerHolder over manual memory allocation in shippable
4 8 code where possible. Fixes #235.
5 9  
... ...
libqpdf/SecureRandomDataProvider.cc
... ... @@ -62,18 +62,21 @@ class WindowsCryptProvider
62 62 #endif
63 63 {
64 64 if (! CryptAcquireContext(&crypt_prov,
65   - "Container",
66   - NULL,
67   - PROV_RSA_FULL,
68   - CRYPT_NEWKEYSET))
  65 + "Container",
  66 + NULL,
  67 + PROV_RSA_FULL,
  68 + CRYPT_NEWKEYSET))
69 69 {
70 70 throw std::runtime_error(
71   - "unable to acquire crypt context with new keyset");
  71 + "unable to acquire crypt context with new keyset: " +
  72 + getErrorMessage());
72 73 }
73 74 }
74 75 else
75 76 {
76   - throw std::runtime_error("unable to acquire crypt context");
  77 + throw std::runtime_error(
  78 + "unable to acquire crypt context: " +
  79 + getErrorMessage());
77 80 }
78 81 }
79 82 }
... ... @@ -84,6 +87,24 @@ class WindowsCryptProvider
84 87 }
85 88  
86 89 HCRYPTPROV crypt_prov;
  90 +
  91 + private:
  92 + std::string getErrorMessage()
  93 + {
  94 + DWORD errorMessageID = ::GetLastError();
  95 + LPSTR messageBuffer = nullptr;
  96 + size_t size = FormatMessageA(
  97 + FORMAT_MESSAGE_ALLOCATE_BUFFER |
  98 + FORMAT_MESSAGE_FROM_SYSTEM |
  99 + FORMAT_MESSAGE_IGNORE_INSERTS, NULL, errorMessageID,
  100 + MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
  101 + reinterpret_cast<LPSTR>(&messageBuffer), 0, NULL);
  102 + std::string message(messageBuffer, size);
  103 + LocalFree(messageBuffer);
  104 + return ("error number " +
  105 + QUtil::int_to_string_base(errorMessageID, 16) +
  106 + ": " + message);
  107 + }
87 108 };
88 109 #endif
89 110  
... ...