HI,
I try to import key from blob using "Microsoft Software Key Storage Provider". This is my code:
byte[] keyBlob = File.ReadAllBytes("c:\\privkey.der"); string container = "MyContainer"; CngProvider myKSP = new CngProvider("Microsoft Software Key Storage Provider"); if (!CngKey.Exists(container, myKSP)) { CngKeyCreationParameters keyParams = new CngKeyCreationParameters(); //Will allow export of full keypair to the file later on keyParams.ExportPolicy = CngExportPolicies.AllowPlaintextExport; keyParams.KeyCreationOptions = CngKeyCreationOptions.None; //Set the Key Storage Provider keyParams.Provider = myKSP; keyParams.KeyUsage = CngKeyUsages.Signing; //Set the RSA keysize to 2048 CngProperty keySizeProperty = new CngProperty("Length", BitConverter.GetBytes(2048), CngPropertyOptions.None); keyParams.Parameters.Add(keySizeProperty); //Most important step -> import the keyblob as byte[] CngProperty keyBlobProperty = new CngProperty(CngKeyBlobFormat.Pkcs8PrivateBlob.Format, keyBlob, CngPropertyOptions.None); keyParams.Parameters.Add(keyBlobProperty); CngKey myCNGKey = CngKey.Create(new CngAlgorithm("RSA"), container, keyParams); }
Create operation throws an exception:
System.Security.Cryptography.CryptographicException was unhandledHResult=-2146893783
Message=The requested operation is not supported.
Source=System.Core
StackTrace:
at System.Security.Cryptography.NCryptNative.SetProperty(SafeNCryptHandle ncryptObject, String propertyName, Byte[] value, CngPropertyOptions propertyOptions)
at System.Security.Cryptography.CngKey.SetKeyProperties(SafeNCryptKeyHandle keyHandle, CngKeyCreationParameters creationParameters)
at System.Security.Cryptography.CngKey.Create(CngAlgorithm algorithm, String keyName, CngKeyCreationParameters creationParameters)
at ConsoleApplication4.Program.Main(String[] args) in c:\Users\mkaszubs\Documents\Visual Studio 2012\Projects\ConsoleApplication1\ConsoleApplication4\Program.cs:line 48
at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
InnerException:
This code comes from different post on this forum. Interesting part is that I was able to Import this key using
CngKey key = CngKey.Import(keyBlob, CngKeyBlobFormat.Pkcs8PrivateBlob, myKSP);
So it looks like blob is formated correctly.
My OS: Windows Server 2008 R2 Enterpriese
.Net: Framework 4.5
Any suggestion what can be wrong here?
Regards,
Marcin