SecureBlackbox 16: Why does the signing or decryption operation fail when my code is run as a Windows service?

Note: This article applies only to SecureBlackbox Legacy. For future development please consider using the latest version.

If you use certificates using the Windows CryptoAPI interface (the TElWinCertStorage class), you can face a problem in which your code works fine in the regular application but fails with an error when running within the system service or in IIS (Internet Information Server).

A common reason is that the service has no access to the certificate.

Certificates are stored in the Windows CryptoAPI in several stores, the most well-known of which are the HKEY_CURRENT_USER and HKEY_LOCAL_MACHINE keys in the Windows registry. As the name suggests, HKEY_CURRENT_USER stores are accessible only to a certain user account, and HKEY_LOCAL_MACHINE stores are available all across the system.

By default when you import the certificate to the system, it's stored in the HKEY_CURRENT_USER store. Such a certificate won't be accessible from the service.

Solutions

  • Import the certificate to the HKEY_LOCAL_MACHINE store using MMC's "Certificates" applet.
  • Make your code impersonate another user for the purpose of signing.
  • Run the service under the user account of a certain user and import the certificate to that user's certificate store.

We mention option 2 here for a reason. A fair number of drivers of cryptographic devices (SmartCards and USB CryptoTokens) map the certificates stored on the device into the Windows CryptoAPI stores of the currently logged in user, and this behavior sometimes can not be changed. This means that your code, being executed under a service account, won't ever get access to the device certificates via the CryptoAPI, unless it can impersonate a local interactive user with access to the certificates of the hardware device.

The alternative to the latter problem is to access device certificates not via the CryptoAPI but via the PKCS#11 interface, which is also supported by SecureBlackbox.

We appreciate your feedback.  If you have any questions, comments, or suggestions about this article please contact our support team at kb@nsoftware.com.