I'm trying to generate a self-signed certificate on the fly (programmatically) in a C# assembly (targeting .NET 4.0
), to serve as a root CA to generate other certificates. The certificate doesn't need to be persisted in the Windows certificate store, I'll export it as a file.
Reading through this question (and in particular, @dthorpe's answer), I decided to give a try to CLR Security.
The CLR Security
library put an extension method on CngKey class to generate a self-signed certificate, but I couldn't succeed in creating an instance of CngKey
with:
var key = CngKey.Create(CngAlgorithm.Sha1); //same with Sha256, Sha512 and MD5
//or
var key = CngKey.Create(CngAlgorithm.Sha1, null, new CngKeyCreationParameters()
{
ExportPolicy = CngExportPolicies.AllowExport,
KeyUsage = CngKeyUsages.AllUsages,
KeyCreationOptions = CngKeyCreationOptions.MachineKey,
});
Any of these lines raises the exception:
System.Security.Cryptography.CryptographicException was unhandled
HResult=-2146893783
Message=The requested operation is not supported.
Source=System.Core
StackTrace:
at System.Security.Cryptography.NCryptNative.CreatePersistedKey(SafeNCryptProviderHandle provider, String algorithm, String name, CngKeyCreationOptions options)
at System.Security.Cryptography.CngKey.Create(CngAlgorithm algorithm, String keyName, CngKeyCreationParameters creationParameters)
at System.Security.Cryptography.CngKey.Create(CngAlgorithm algorithm)
at Tests.Program.Main(String[] args) at Program.cs:line 51
Searching through SO and the internet, I've checked the following:
- I'm running a Windows 7 box (so it supports RPC as per MSDN)
- Tried on a Windows Server 2012 box, same error
- The process is running as admin (so it have access to all cert storages, anyway)
- The services
CNG Key Isolation
andRemote Procedure Call (RPC)
are running
Any help would be appreciated.