Search code examples
c#cng

CNGKey.Create won't persist


I'm playing with CNGKey and the storage. I would like to store the key, and later retrieve it for encryption.
I am usingCngKey.Create and I see that it is persisted in the file system. To test access to it, immediately after the Create command I get false for CngKey.Existsm using visual studio's 'watch' window.
This happens for both RSA, using Microsoft's built in enum, and AES, using "AES" string.

My code for AES:

CngKeyCreationParameters keyParams = new CngKeyCreationParameters
{
    ExportPolicy = CngExportPolicies.AllowExport,
    KeyCreationOptions = CngKeyCreationOptions.MachineKey | CngKeyCreationOptions.OverwriteExistingKey,
    Provider = CngProvider.MicrosoftSoftwareKeyStorageProvider,
    //KeyUsage = CngKeyUsages.Decryption
};
CngAlgorithm aesAlgorithm = new CngAlgorithm("AES");
CngKey.Create(aesAlgorithm, "mykeyAES", keyParams);

My code for RSA:

CngKeyCreationParameters keyParams = new CngKeyCreationParameters
{
    ExportPolicy = CngExportPolicies.AllowExport,
    KeyCreationOptions = CngKeyCreationOptions.MachineKey | CngKeyCreationOptions.OverwriteExistingKey,
    Provider = CngProvider.MicrosoftSoftwareKeyStorageProvider,
    //KeyUsage = CngKeyUsages.Decryption
};
if (!CngKey.Exists(keyName, CngProvider.MicrosoftSoftwareKeyStorageProvider))
{
    CngKey key = CngKey.Create(CngAlgorithm.Rsa, keyName, keyParams);
}

The only relevant information I get from searching the web, is getting to the same questions on SO which don't help me much with my specific case. Appreciate any help!

Edit:

According to @Martheen's reply, Open has changed to:

CngKey key = CngKey.Open(keyName, CngProvider.MicrosoftSoftwareKeyStorageProvider, CngKeyOpenOptions.MachineKey);

I'm getting true on CngKey.Exists but get an exception 'keypair does not exist'


Solution

  • If you create the key as machine-wide, you'd have to specify it too on accessing them

    CngKey.Exists("mykeyAES", CngProvider.MicrosoftSoftwareKeyStorageProvider, CngKeyOpenOptions.MachineKey));
    

    and

    CngKey.Open("mykeyRSA", CngProvider.MicrosoftSoftwareKeyStorageProvider, CngKeyOpenOptions.MachineKey));