I had a problem using a machine-level RSA key container when storing only the public key of a public / private key pair.
The following code creates a public / private pair and extracts the public key from this pair. The pair and public key are stored in separate key containers. The keys are then retrieved from these key containers, after which they should be the same as the keys included in the containers.
The code works when CspProviderFlags.UseDefaultKeyContainer is specified for CspParameters.Flags (i.e. the key returned from the PublicKey container is the same), but when CspProviderFlags.UseMachineKeyStore is specified for CspParameters.Flags , the key read from PublicKey is different.
Why is the behavior different and what do I need to do differently to get the public key from the RSA key container at the machine level?
var publicPrivateRsa = new RSACryptoServiceProvider(new CspParameters() { KeyContainerName = "PublicPrivateKey", Flags = CspProviderFlags.UseMachineKeyStore //Flags = CspProviderFlags.UseDefaultKeyContainer } ) { PersistKeyInCsp = true, }; var publicRsa = new RSACryptoServiceProvider(new CspParameters() { KeyContainerName = "PublicKey", Flags = CspProviderFlags.UseMachineKeyStore //Flags = CspProviderFlags.UseDefaultKeyContainer } ) { PersistKeyInCsp = true }; //Export the key. publicRsa.ImportParameters(publicPrivateRsa.ExportParameters(false)); Console.WriteLine(publicRsa.ToXmlString(false)); Console.WriteLine(publicPrivateRsa.ToXmlString(false)); //Dispose those two CSPs. using (publicRsa) { publicRsa.Clear(); } using (publicPrivateRsa) { publicRsa.Clear(); } publicPrivateRsa = new RSACryptoServiceProvider(new CspParameters() { KeyContainerName = "PublicPrivateKey", Flags = CspProviderFlags.UseMachineKeyStore //Flags = CspProviderFlags.UseDefaultKeyContainer } ); publicRsa = new RSACryptoServiceProvider(new CspParameters() { KeyContainerName = "PublicKey", Flags = CspProviderFlags.UseMachineKeyStore //Flags = CspProviderFlags.UseDefaultKeyContainer } ); Console.WriteLine(publicRsa.ToXmlString(false)); Console.WriteLine(publicPrivateRsa.ToXmlString(false)); using (publicRsa) { publicRsa.Clear(); } using (publicPrivateRsa) { publicRsa.Clear(); }
c # cryptography rsacryptoserviceprovider
Andrew Kimball Feb 16 '10 at 16:50 2010-02-16 16:50
source share