Search code examples
c#asp.netencryptionencryption-asymmetric

How to store private key in Key Container?


I want to store a private key in a key container to create a signature over data for an asp.net website.

//First I Read PrivateKey from text file that i Uploaded with FileUpload(fuPrivateKey)
var pk = Encoding.UTF8.GetString(fuPrivateKey.FileBytes);
CspParameters csp = new CspParameters();
csp.KeyContainerName = "PrivateKeyForSignature";
DSACryptoServiceProvider rsa = new DSACryptoServiceProvider(csp);//error
rsa.FromXmlString(pk);

but I got the following error at line of DSACryptoServiceProvider rsa = new DSACryptoServiceProvider(csp);:

The specified cryptographic service provider (CSP) does not support this key algorithm.

I have used this method for storing an RsaCryptoServiceProvider key without any problem. However when I want to use it for DSA it doesn't work.


Solution

  • If I take a look at the default (no argument) constructor of CspParameters then I get this text:

    This form of CspParameters initializes the ProviderType field to a value of 24, which specifies the PROV_RSA_AES provider. This default provider is compatible with the Aes algorithm.

    If I look up the constructor that accepts a 32 bit integer I get:

    Initializes a new instance of the CspParameters class with the specified provider type code.

    ...

    To specify a provider compatible with the DSA algorithm, pass a value of 13to the dwTypeIn parameter.

    So it seems to me this can be solved by calling the right constructor of CspParameters with the right code.