3

I am currently using RSACryptoServiceProvider and I want to change to RSACng. I am using it to sign data. The reason for the change is that I am using Pkcs1 padding and I understand that Pss padding is preferred. We are undergoing security audits.

My question is how do I instantiate RSACng so that it uses the same private / public key each time?

With RSACryptoServiceProvider I am doing:

CspParameters cp = new CspParameters();  
cp.KeyContainerName = "ContainerName";  
RSACryptoServiceProvider RSA = new RSACryptoServiceProvider(cp);

passing in the container name means it uses the key that persists in the in the container store on the machine.

With RSACng, I tried this, but I get an exception: "The requested operation is not supported"

RSACng RSA = new RSACng(CngKey.Create(CngAlgorithm.Sha256, ContainerName));

I just need to be able to pass the store key name so it uses the same key each time instead of generating a new key.

BrianK
  • 2,357
  • 3
  • 32
  • 41

1 Answers1

1

If you want to create a named/persisted RSA key with CNG:

private static RSA CreatePersistedRSAKey(string name, int keySizeInBits)
{
    CngKeyCreationParameters creationParameters = new CngKeyCreationParameters
    {
        // This is what an ephemeral key would have had
        // (allows ExportParameters(true) to succeed). Adjust as desired.
        //
        // The default is not exportable (only applies to the private key)
        ExportPolicy =
            CngExportPolicies.AllowExport | CngExportPolicies.AllowPlaintextExport,
    };

    creationParameters.Parameters.Add(
        new CngProperty(
            "Length",
            BitConverter.GetBytes(keySizeInBits),
            CngPropertyOptions.Persist));

    // RSACng will extract the data it needs from this key object,
    // but doesn't take ownership
    using (CngKey key = CngKey.Create(CngAlgorithm.Rsa, name, creationParameters))
    {
        return new RSACng(key);
    }
}

This skips the parts where you would do a try/catch around a call to CngKey.Open, or might want to delete the key (open it with CngKey.Open, and call Delete on the CngKey instance).

(CngAlgorithm.Rsa was added in net46. If you're on an older version then an equivalent would be new CngAlgorithm("RSA"))

bartonjs
  • 30,352
  • 2
  • 71
  • 111