I have been struggling to create a CNGKey with a certain private key and with a key name can someone please assist me. Below is the code. I need to create this cngkey on multiple servers with the specific private key. When the key is created it does not use the private key that was specified but it creates a new private key
string importKeyName = commandLineParser.Contains("KeyName") ? commandLineParser["KeyName"] : string.Empty;
if (!string.IsNullOrWhiteSpace(importKeyName))
{
if (!CngKey.Exists(importKeyName))
{
XDocument xKey = XDocument.Load(Path.Combine(Environment.CurrentDirectory, "CNGKeys.xml"));
string privateKey = xKey.Element("Keys").Element(importKeyName).Element("Private").Value;
string publicKey = xKey.Element("Keys").Element(importKeyName).Element("Public").Value;
CngKeyCreationParameters creationParameters = new CngKeyCreationParameters()
{
KeyUsage = CngKeyUsages.AllUsages,
Provider = CngProvider.MicrosoftSoftwareKeyStorageProvider,
ExportPolicy = CngExportPolicies.AllowPlaintextExport,
KeyCreationOptions = CngKeyCreationOptions.OverwriteExistingKey,
};
creationParameters.Parameters.Add(new CngProperty(CngKeyBlobFormat.EccPrivateBlob.Format, Convert.FromBase64String(privateKey), CngPropertyOptions.CustomProperty));
creationParameters.Parameters.Add(new CngProperty(CngKeyBlobFormat.EccPublicBlob.Format, Convert.FromBase64String(publicKey), CngPropertyOptions.CustomProperty));
CngKey cngKey = CngKey.Create(CngAlgorithm.ECDiffieHellmanP521, importKeyName, creationParameters);
}
}