Use of the RSACryptoServiceProvider in our Samples

Coordinator
Jul 27, 2007 at 8:59 PM
I have had a couple of people ask about how our use of the KeyHolderPrincipal works in the SecPAL samples. Our samples use code similar to this for creating KeyHolderPrincipals:
private static KeyHolderPrincipal userPrincipal =
new KeyHolderPrincipal(new RSACryptoServiceProvider(), "K-User");

In this case the .NET Framework gives you a randomly-generated key pair in a random (and transient) key container. But if you provide a key container name then the .NET Framework will access the key that’s present in the container (and if the container doesn’t exist it’ll create it and randomly generate a persistent key in that container for you). I have included a code sample below that shows how to create and persist a key. As a side note, the CspParameters class also allows a provider to be specified, which could allow you to access keys stored on a smart card or in a crypto hardware module (etc).

using System;
using System.Collections.Generic;
using System.Text;
using System.Security.Cryptography;

namespace RSATest
class Program
{
static void Main(string[] args)
{

string publicKey = InitializeKey();
Console.WriteLine("The RSA key {0} was persisted in the container JasonsTest.", publicKey);
Console.WriteLine(publicKey);
// LOGOFF / REBOOT / etc
LoadKey(publicKey);
Console.ReadLine();
}

private static string InitializeKey()
{
CspParameters cspParams = new CspParameters();
cspParams.KeyContainerName = "JasonsTest";
RSACryptoServiceProvider RSAalg = new RSACryptoServiceProvider(cspParams);
string publicKey = RSAalg.ToXmlString(false);
return publicKey;
}

private static void LoadKey(string publicKey)
{
CspParameters cspParams = new CspParameters();
cspParams.KeyContainerName = "JasonsTest";
RSACryptoServiceProvider rsaCSP = new RSACryptoServiceProvider(cspParams);
rsaCSP.FromXmlString(publicKey);
publicKey = rsaCSP.ToXmlString(false);
Console.WriteLine("Key {0} was read successfully", publicKey);
}
}
}