且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何存储在机器级RSA密钥容器的公共密钥

更新时间:2023-01-31 19:00:44

看来,关键的容器不适用于这个目的(这是由隐含的如何:存储对称密钥在密钥容器,从.NET Framework开发人员指南,并通过的 MSDN上一个disccusion)。



其他机制,如存储在XML文件中的关键,需要使用以实现这一目标。


I'm having 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 that pair. The pair and the public key are stored in separate key containers. The keys are then obtained from those key containers at which point they should be the same as the keys going into the containers.

The code works when CspProviderFlags.UseDefaultKeyContainer is specified for CspParameters.Flags (i.e. the key read back out from the PublicKey container is the same), but when CspProviderFlags.UseMachineKeyStore is specified for CspParameters.Flags the key read back from PublicKey is different.

Why is the behaviour different, and what do I need to do differently to retrieve the public key from a machine-level RSA key container?

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();
}

It seems that key containers are not intended for this purpose (this is implied by "How to: Store Asymmetric Keys in a Key Container" from the .NET Framework Developer's Guide, and confirmed by a disccusion on MSDN).

Other mechanisms, such as storing the key in an XML file, need to be used to achieve this goal.