Search code examples
c#securityencryptioncng

Can someone explain C# CngKey.Import please?


I'm encrypting a db using Always Encrypted with the master key in the software ksp.

The key is created with CngKey.Create, I can also export it, but I'm stuck after that. Using the CngKey.Import creates a non-named key, meaning IsEphemeral=true, so the key gets destroyed when there is no more handles.

How can I'm import the key as a named key that will be persisted?

The ultimate goal is to be able to export the key used as the master encryption key with the db and give that along with the db backup to party x who wants to use the db. The tool should then recreate the key in party x's machine.


Solution

  • I believe (based on vague recollection and a similar answer) that you can make Create import at the same time, unless it's an encrypted PKCS#8.

    byte[] exported = key.Export(blobType);
    

    Send exported and blobType to somewhere else.

    var keyParams = new CngKeyCreationParameters();
    // whatever else you want to assign here.
    
    // Add an import to the create step.
    keyParams.Properties.Add(new CngProperty(blobType.Format, exported, CngPropertyOptions.None));
    
    CngKey key = CngKey.Create(algorithm, keyName, keyParams);