3

How can I export CngKey to PKCS#8 with encryption?

static void Main(string[] args)
    {
        CngKeyCreationParameters ckcParams = new CngKeyCreationParameters()
        {
            ExportPolicy = CngExportPolicies.AllowExport,
            KeyCreationOptions = CngKeyCreationOptions.None,
            KeyUsage = CngKeyUsages.AllUsages,                
        };
        ckcParams.Parameters.Add(new CngProperty("Length", BitConverter.GetBytes(2048), CngPropertyOptions.None));

        myCngKey = CngKey.Create(CngAlgorithm.Rsa, "theCngKey", ckcParams);

        byte[] privatePlainTextBlob = myCngKey.Export(CngKeyBlobFormat.Pkcs8PrivateBlob);
 }

Setting the ExportPolicy to AllowPlainTextExport allows the key to be exported, but only in plain text. I would like to create a PCKS8 blob which is encrypted with a symmetric key.

Thanks

Rowan Smith
  • 1,815
  • 15
  • 29

1 Answers1

1

Since CngKey.Export doesn't accept a password, you'd have to manually P/Invoke to NCryptExportKey, providing a NCRYPTBUFFER_PKCS_SECRET value (Unicode/UCS-2 encoded password with explicit null terminator).

http://source.dot.net/#System.Security.Cryptography.Cng/Common/System/Security/Cryptography/ECCng.ImportExport.cs,8b172741466df7a1 can be used as an example of building the parameter list. It's not fun.

bartonjs
  • 30,352
  • 2
  • 71
  • 111
  • Thanks! I had great success with this. When I just have a NCRYPTBUFFER_PKCS_SECRET value, the output is identical to CngKey.Export(). It would seem that I also need to provide a NCRYPTBUFFER_PKCS_ALG_OID and possibly a NCRYPTBUFFER_PKCS_ALG_PARAM. But I can't find anywhere what I should use for these parameters. I want to do an AES256 PKCS8. – Rowan Smith Jun 02 '17 at 03:11