This post is more a reminder for me than anything else, but you may find it useful if you are scripting certificate-management tasks on Windows.

The Certificate Manager snap-in for Windows allows you to manage permissions for certificates.  This is important if you want to, for example, grant your ASP.NET application the ability to use a private key from the certificate store in order to perform encryption/decryption operations.  While it is easy to script out many certificate-related operations with the makecert and other command-line tools from Microsoft, I failed to find anything that would allow me to change actual certificate permissions. 

Did you know that Windows actually keeps the private keys for your certificates on the filesystem?  Yeah, I didn’t either.  It turns out that you can simply change permissions on the private key file to change permissions for the certificate itself.  This is easy to do using the Icacls tool.

Unfortunately, it is not so easy to determine which key file corresponds to which key in your certificate store.  The key files are buried under the C:\Users directory and have intuitive names like  8aeda5eb81555f14f8f9960745b5a40d_38f7de48-5ee9-452d-8a5a-92789d7110b1.  I haven’t found a built-in way to figure out which file belongs to which key, but there is a sample tool available from Microsoft that can help: FindPrivateKey.exe, which you can download from Microsoft Download Center as part of the WCF and WF samples pack.  The samples are all in source form, so you’ll need to compile the tool using Visual Studio.

Once you have compiled the tool, the following Powershell script will find the path to your private key and set the permissions so it can be read by IIS:

$keyName = "YourKeyNameHere"

$keyPath = .\FindPrivateKey My LocalMachine -n "CN=$keyName" -a

icacls $keyPath /grant "IIS_IUSRS:(F)"

Simple enough, right?