开发者

How to encrypt and decrypt custom configuration files (XML files) in C#

开发者 https://www.devze.com 2022-12-18 03:14 出处:网络
I am new to the forums. I\'ve just started working on C# and webservices for the past 3 months and I\'ve got a great web service rearing to go. Unfortunately, there is a custom \"configuration\" file

I am new to the forums.

I've just started working on C# and webservices for the past 3 months and I've got a great web service rearing to go. Unfortunately, there is a custom "configuration" file (really an XML file) that we use to store our connection strings.

We don't want to use the web.config connectionstring section because the class and the associated xml file that was written in house, will be used by other projects not just web services. The problem is I need to encrypt the username and passwords of the "configuration" XML file and decrypt it in my C# code.

Suffice to say the XML file has the following structure ...

<?xml version='1.0'?>
<!--
TEST ENVIRONMENT
-->
<thesystem>
   <connectionString string="Data Source=( DESCRIPTION = ( ADDRESS_LIST = ( ADDRESS = ( PROTOCOL = TCP )( HOST = {0} )( PORT = {1} ) ) )( CONNECT_DATA = ( SERVER = DEDICATED )( SERVICE_NAME = {2} ) ) ); User Id= {3}; Password = {4};"/>
   <oracleDetails>
     <site name="thesite">
       <schema dbname="thedb"    dbHost="99.99.99.99" dbPort="9999" dbServiceName="SYSTEMSITE" dbUsername="xxx" dbPassword="yyy"/>
     </site>
   </oracleDetails>
</thesystem>

I've looked on the web and managed to "cheat" around a way to encrypt the file using aspnet_regiis.exe

ie:

C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727>aspnet_regiis 开发者_运维问答-pef oracleDetails . -prov DataProtectionConfigurationProvider

Encrypting configuration section... Succeeded!

I got this to work by renaming the tag to and renaming the xml file to web.config. I tricked ASP.net to think I am encrypting a web configuration file.

The problem now is how do I decrypt it in C#?

I've tried using the following ...

Configuration _myConfig = ConfigurationManager.OpenExeConfiguration("OURSYSTEM.config");

where OURSYSTEM.config is the XML file above.

It program throws an error saying it cannot locate the file. And besides, the OpenExeConfiguration is more for Win apps with the app.config file.


After you run the aspnet_regiis -pef oracleDetails . -prov DataProtectionConfigurationProvideris the config XML encrypted? Most likely it is, and problem then is that your ASP.Net cannot decrypt it and that ultimately is a key access issue. Make sure you encrypt it using credentials the app pool has access to. Ie. if your ASP app pool runs as user foo, then you must run aspnet_regiis as the same user.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号