Skip to content

Commit

Permalink
Provide error message in Windows crypto code (fixes qpdf#286)
Browse files Browse the repository at this point in the history
Thanks to github user zdenop for supplying some additional
error-handling code.
  • Loading branch information
jberkenbilt committed Jun 22, 2019
1 parent 6c39aa8 commit 7bd38a3
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 6 deletions.
4 changes: 4 additions & 0 deletions ChangeLog
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
2019-06-22 Jay Berkenbilt <[email protected]>

* Provided a more useful error message when Windows can't get
security context. Thanks to user zdenop for supplying some code.
Fixes #286.

* Favor PointerHolder over manual memory allocation in shippable
code where possible. Fixes #235.

Expand Down
33 changes: 27 additions & 6 deletions libqpdf/SecureRandomDataProvider.cc
Original file line number Diff line number Diff line change
Expand Up @@ -62,18 +62,21 @@ class WindowsCryptProvider
#endif
{
if (! CryptAcquireContext(&crypt_prov,
"Container",
NULL,
PROV_RSA_FULL,
CRYPT_NEWKEYSET))
"Container",
NULL,
PROV_RSA_FULL,
CRYPT_NEWKEYSET))
{
throw std::runtime_error(
"unable to acquire crypt context with new keyset");
"unable to acquire crypt context with new keyset: " +
getErrorMessage());
}
}
else
{
throw std::runtime_error("unable to acquire crypt context");
throw std::runtime_error(
"unable to acquire crypt context: " +
getErrorMessage());
}
}
}
Expand All @@ -84,6 +87,24 @@ class WindowsCryptProvider
}

HCRYPTPROV crypt_prov;

private:
std::string getErrorMessage()
{
DWORD errorMessageID = ::GetLastError();
LPSTR messageBuffer = nullptr;
size_t size = FormatMessageA(
FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS, NULL, errorMessageID,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
reinterpret_cast<LPSTR>(&messageBuffer), 0, NULL);
std::string message(messageBuffer, size);
LocalFree(messageBuffer);
return ("error number " +
QUtil::int_to_string_base(errorMessageID, 16) +
": " + message);
}
};
#endif

Expand Down

0 comments on commit 7bd38a3

Please sign in to comment.