PRB: Cannot Import Directory Service Agent Key from XML (327652)



The information in this article applies to:

  • Microsoft .NET Framework Class Libraries 1.0
  • Microsoft .NET Framework Class Libraries 1.1

This article was previously published under Q327652

SYMPTOMS

When you import an XML-formatted directory service agent (DSA) private key, DSACryptoServiceProvider may raise an exception on the FromXmlString() method although the ToXmlString() was used to export the DSA private key.

The following exception is raised:

System.Security.Cryptography.CryptographicException: Bad Key.

CAUSE

This exception occurs when you use the default CspParameters constructor to create an instance of DSACryptoServiceProvider constructor.

The default CspParameters constructor sets the provider type to PROV_RSA_FULL, which uses the RSA Crypto Service Provider (instead of using the DSA Crypto Service Provider). The resulting XML private key that is returned from DSACryptoServiceProvider.ToXmlString() is an RSA key, which then raises an exception when you re-import it with DSACryptoServiceProvider.FromXmlString() because it is not recognized as a DSA key.

RESOLUTION

To resolve the problem, do not use the default CspParameters constructor. You can create an instance of CspParameters with a provider type. Creating an instance of CspParameters with a value of 13 sets the provider type to PROV_DSS_DH, which uses the DSA provider and fixes the problem.

STATUS

This behavior is by design.

MORE INFORMATION

Workaround

The following C# sample code uses 13 (PROV_DSS_DH) to work around the problem:
// This constructor uses the DSA provider type (13)
CspParameters parameters = new CspParameters(13);

parameters.KeyContainerName = "DSAKeyContainer";

DSACryptoServiceProvider dsa = new DSACryptoServiceProvider(parameters);

Console.WriteLine(dsa.ToXmlString(true));

DSACryptoServiceProvider dsa1 = new DSACryptoServiceProvider();

// This executes successfully.
dsa1.FromXmlString(dsa.ToXmlString(true)); 
				

Steps to Reproduce the Behavior

Use the following C# sample code:
// The default constructor uses the default provider type, that is 1 (RSA provider).
CspParameters parameters = new CspParameters();

parameters.KeyContainerName = "DSAKeyContainer";

DSACryptoServiceProvider dsa = new DSACryptoServiceProvider(parameters);

Console.WriteLine(dsa.ToXmlString(true));

DSACryptoServiceProvider dsa1 = new DSACryptoServiceProvider();

// This raises an exception.
dsa1.FromXmlString(dsa.ToXmlString(true)); 
				

Modification Type:MajorLast Reviewed:10/17/2003
Keywords:kbAPI kbCrypt kbKernBase kbprb KB327652 kbAudDeveloper