如何从代码中设置RSAProtectedConfigurationProvider的密钥大小

时间:2013-02-19 01:12:30

标签: c# security web-config rsa

我的应用程序可以保护选定的配置文件。这是使用SectionInformation.ProtectSection方法为加载的Configuration的指定部分完成的。我正在使用标准提供商RsaProtectedConfigurationProvider

代码非常简单 - 与example on MSDN非常相似。

有没有办法设置提供商应该使用的密钥大小?据我所知,RSA的默认值是1024.我需要将其设置为2048或更大。

当我们使用 asp_regiis.exe 时,可以使用命令行选项 -size 完成类似操作。但我需要从代码中做到这一点。也许有任何方法可以配置RsaProtectedConfigurationProvider或预创建密钥并以某种方式将其注入默认密钥存储区,因此下次使用SectionInformation.ProtectSection将会赶上它...

感谢您的任何建议或示例。

1 个答案:

答案 0 :(得分:1)

RSAProtectedConfigurationProvider提供了两种不同的方法。一个名为AddKey的名称可用于在容器内创建一个键。如果您将密钥标记为可导出,则可以稍后使用ExportKey方法获取该密钥并将其存储在其他位置。

如果您已有现有密钥,则可以使用ImportKey方法。它将接受一个类似于ExportKey的XML blob。

RsaProtectedConfigurationProvider使用默认容器名称 NetFrameworkConfigurationKey (如果未提供)。因此,如果您预先创建密钥并将其添加到该容器中,则提供程序应在您使用它时将其取出。

// Same properties as .NET uses to load the key
CspParameters csp = new CspParameters();
csp.KeyContainerName = "NetFrameworkConfigurationKey"; 
csp.KeyNumber = 1;
csp.ProviderType = 1;

// Create the new key, and save it in the key store
rsa = new RSACryptoServiceProvider(2048, csp);
rsa.PersistKeyInCsp = true;
rsa.Clear();