How to encrypt sections of our app.config inside our asp.net console application

john john 1,021 Reputation points
2021-04-27T09:11:39.387+00:00

I have the following section inside my asp.net console application's app.config, to store our APIKey:-

<configuration>
  <configSections>
    <sectionGroup name="customAppSettingsGroup">
      <section name="customAppSettings"
               type="System.Configuration.NameValueSectionHandler,System" />
    </sectionGroup>
  </configSections>
  <customAppSettingsGroup>
    <customAppSettings>
      <add key="APIKey" value="****" />
    </customAppSettings>
  </customAppSettingsGroup>
  <appSettings>
</appSettings>

but i have 2 questions:-

1) how i can access this section inside my code?

2) Can i encrypt this section both inside visual studio and inside the live server?

Thanks

Developer technologies | ASP.NET | Other
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Anonymous
    2021-04-28T06:24:29.523+00:00

    Hi @john john ,

    According to your description, I create a simple demo to produce your problem, you could try something like this:

    <?xml version="1.0" encoding="utf-8" ?>  
    <configuration>  
      <configSections>  
        <!--<sectionGroup name="customAppSettingsGroup" >-->  
        <section name="customAppSettings" type="System.Configuration.NameValueSectionHandler, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />  
        <!--</sectionGroup>-->  
      </configSections>  
      <!--<customAppSettingsGroup>-->  
      <customAppSettings>  
        <add key="APIKey" value="*****" />  
      </customAppSettings>  
      <!--</customAppSettingsGroup>-->  
      <appSettings>  
      </appSettings>  
      <startup>  
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.2" />  
      </startup>  
    </configuration>  
    

    And use these code to get the key value:

    NameValueCollection section = ConfigurationManager.GetSection("customAppSettings") as NameValueCollection;  
    string key = section["APIKey"];  
    

    Regarding its encryption and decryption, I think you could try to use SectionInformation.ProtectSection(String) Method. About how to call Data Protection API (DPAPI), you could read this bolg to learn a complete example: How to encrypt and decrypt data using DPAPI in C# or VB.NET

    Best regards,
    Xudong Peng


    If the answer is helpful, please click "Accept Answer" and upvote it.

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.