karolyzz
karolyzz

Reputation: 510

Importing exported CngKey to RSA and exporting it again

I export a key in CngKeyBlobFormat.Pkcs8PrivateBlob format, then try to import this information into a new CngKey and then I try to export the new key again. Problem is, when you simply import a key with CngKey.Import() you can't choose the parameters, nor the name of the key, thus I can't export it again as the default parameters don't let you do so. So I wrote the following code:

// Import key into RSACng rsa
var key = rsa.Key.Export(CngKeyBlobFormat.Pkcs8PrivateBlob);

CngProvider cp = new CngProvider("NewProvider");
CngKeyCreationParameters ckcp = new CngKeyCreationParameters() { ExportPolicy=CngExportPolicies.AllowPlaintextExport, Provider=cp};
ckcp.Parameters.Add(new CngProperty(CngKeyBlobFormat.Pkcs8PrivateBlob.Format, key, CngPropertyOptions.None));
CngKey cngKey2 = CngKey.Create(CngAlgorithm.Rsa, "OldKey", ckcp);

RSACng rsa2 = new RSACng(cngKey2);
var exportedKey = rsa2.Key.Export(CngKeyBlobFormat.Pkcs8PrivateBlob);
// exportedKey.Equals(key) == true

I get an error on CngKey.Create:

System.Security.Cryptography.CryptographicException: 'Unknown error "-1073741275".

Upvotes: 0

Views: 1012

Answers (1)

bartonjs
bartonjs

Reputation: 33098

It's weird that it reported as an unknown error. That value is STATUS_NOT_FOUND ("The object was not found.").

The most likely problem is that you don't have a registered provider named "NewProvider". That's not the name of a key container it's asking for, it's what library should it send the key to.

99% of the time you want CngProvider.MicrosoftSoftwareKeyStorageProvider. 1% of the time you want CngProvider.MicrosoftSmartCardKeyStorageProvider. Almost immeasurably small you want some other value.

Upvotes: 2

Related Questions