2. Using Key Persistence
The implementation classes for the DSA and RSA algorithms are wrappers
around native code contained in the Windows Crypto API. These classes
expose a feature of this API that allows asymmetric key pairs to be
stored persistently by the operating system; the user does not have
to remember the key parameters, which are protected by the Windows
account password.
Relying on the security of the Windows operating system to protect
cryptographic key pairs is not suitable for all projects; projects
that require high levels of security are likely to be affected by the
relative ease with which a Windows password can be attacked. The full
details of the
Windows Crypto API are beyond the scope of this book, but in this
section, we briefly demonstrate how to use the .NET classes to store
key pairs persistently.
The System.Security.Cryptography.CspParameters
class allows you to specify the details of how a key pair should be
stored—there are various options available, but for your
purposes, you require only a name to associate with the keys. The
name relates to the key store, and you can use
any name that suits your needs; the following statements create an
instance of the CspParameters class and set the
key store name to be MyKeys:
# C#
// create the parameters instance
CspParameters x_params = new CspParameters( );
// specify the container name
x_params.KeyContainerName = "MyKeys";
# Visual Basic .NET
' create the parameters instance
Dim x_params As CspParameters = New CspParameters( )
' specify the container name
x_params.KeyContainerName = "MyKeys"
Once you have created your CspParameters instance,
you can use it as the argument to the constructor of the algorithm
implementation class. The final step is to set the
PersistKeyInCsp property to
true, specifying that you want to store the
algorithm's key pair persistently. The following
statements demonstrate how to create an instance of the
RSACryptoServiceProvider class using the
CspParameters instance as an argument and set the
PersistKeyInCsp property:
# C#
// create an instance of the crypto provider class with the csp parameters
RSACryptoServiceProvider x_rsa = new RSACryptoServiceProvider(x_params);
// enable key persistence
x_rsa.PersistKeyInCsp = true;
# Visual Basic .NET
' create an instance of the crypto provider class with the csp parameters
Dim x_rsa As RSACryptoServiceProvider = New RSACryptoServiceProvider(x_params)
' enable key persistence
x_rsa.PersistKeyInCsp = true
The asymmetric implementation classes will create a key pair
automatically before performing any cryptographic operations or
exporting the key parameters. When the key pair is created, it will
be stored persistently and the user will not have to try and remember
(or write down) the key details. This technique can be used only with
classes that build on functionality of the Windows Crypto API;
implementations from third-party companies may not provide this support.