Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set the key size for RSAProtectedConfigurationProvider from the code

My application has a possibility to protect chosen config file. This is done using SectionInformation.ProtectSection method for specified section of loaded Configuration. I'm using standard provider RsaProtectedConfigurationProvider.

The code is quite simple - very similar to example on MSDN.

Is there any way to set the key size that should be used by provider? As I know, the default one for RSA is 1024. I need to set it up to 2048 or bigger.

The similar can be done using command line option -size when we use asp_regiis.exe. But I need to do it from the code. Maybe there is any way to configure RsaProtectedConfigurationProvider or pre-create key and inject it somehow to the default key store so next using of SectionInformation.ProtectSection will catch up it...

Thanks for any advice or examples.

like image 609
kyrylomyr Avatar asked Feb 19 '13 01:02

kyrylomyr


1 Answers

RSAProtectedConfigurationProvider provides two different methods. One called AddKey can be used to create a key inside the container. If you mark the key as exportable you can use ExportKey method later to grab that key and store it somewhere else.

If you already have an existing key, you may be able to use the ImportKey method. It will accept an XML blob much like the one that comes out of ExportKey.

RsaProtectedConfigurationProvider uses a default container name of NetFrameworkConfigurationKey if one isn't provided. So, if you pre-create your key and add it to that container, then the provider should pick it up when you use it.

// 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();
like image 167
Ben Randall Avatar answered Nov 14 '22 02:11

Ben Randall