cryptographypublic-key-encryptionpublic-keyrsacryptoserviceprovidercng

How to persist public key created by RSACng to Local machine or Key Storage provider(KSP)?


I have a Public key and private key pair generated by RSACng class. I am able to persist private key into my KSP(MicrosoftSoftwareKeyStorageProvider) under local machine->(Program Data-> Crypto->RSA->Keys) .But, i am unable to persist public key generated by RSACng. How to persist public key in RSACng to KSP(MicrosoftSoftwareKeyStorageProvider)?

I have already tried persisting public key using CngKey, But it is throwing me 'The operation is not supported'.Please find below the code.

  public static void SaveKeyPairToKSP(KeyGenerationResult keyData, string keyName)
    {
        var myKSP = CngProvider.MicrosoftSoftwareKeyStorageProvider;
        const bool MachineKey = true;

        if (!CngKey.Exists(keyName, myKSP))
        {
            var keyParams = new CngKeyCreationParameters
            {
                ExportPolicy = CngExportPolicies.AllowArchiving,
                KeyCreationOptions = (MachineKey) ? CngKeyCreationOptions.MachineKey : CngKeyCreationOptions.None,
                Provider = myKSP
            };
            keyParams.Parameters.Add(new CngProperty("Length", BitConverter.GetBytes(keyData.KeySize), CngPropertyOptions.None));
            keyParams.Parameters.Add(new CngProperty(CngKeyBlobFormat.GenericPrivateBlob.Format, keyData.PrivateBytes, CngPropertyOptions.Persist));
            //Here is my public key that i want to store in my KSP
            keyParams.Parameters.Add(new CngProperty(CngKeyBlobFormat.GenericPublicBlob.Format, keyData.PublicBytes, CngPropertyOptions.Persist));
            CngKey.Create(CngAlgorithm.Rsa, keyName, keyParams);
        }
    }

But , with above code, it throws me "The operation is not supported" exception. In case, only private key is only added for persistence without public key, code works fine.

Expected result-> I want to persist public key as well as private key in my KSP. actual result-> Only private key is getting persisted. Please do help me on the same. Thanks in advance! Can you please help me out with this?


Solution

  • Microsoft CNG does not support exporting of public keys for assymetric encryption as indicated at https://learn.microsoft.com/en-us/windows/win32/seccng/key-import-and-export

    which states: "For BCryptExportKey to create a persisted key pair, the input key BLOB must contain a private key. Public keys are not persisted."