I am creating a website using MVC5 & EF6. I am also using a shared hosting to publish this website. Now the problem that I have is that my connection string at the moment is sitting in plain text in the web.config file. I am having a very hard time finding a "direct" answer on how I should deal with this.

I have come upon many articles such as this one. The article shows me how to encrypt the Connection Section of my web.config. So I tried following its example and encrypted the mail section it shows in that example. After I ran my code I noticed that my entire web.config file changed.

It use to be like this:

<system.net>
  <mailSettings>
    <smtp from="info@Site.com">
      <network
        host="mail.Site.com"
        port="25"
        userName="info@site.com"
        password="password" />
    </smtp>
  </mailSettings>
</system.net>

and now it is like this:

<mailSettings>
  <smtp configProtectionProvider="RsaProtectedConfigurationProvider">
    <EncryptedData Type="http://www.w3.org/2001/04/xmlenc#Element"
      xmlns="http://www.w3.org/2001/04/xmlenc#">
      <EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#tripledes-cbc" />
      <KeyInfo xmlns="http://www.w3.org/2000/09/xmldsig#">
        <EncryptedKey xmlns="http://www.w3.org/2001/04/xmlenc#">
          <EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#rsa-1_5" />
          <KeyInfo xmlns="http://www.w3.org/2000/09/xmldsig#">
            <KeyName>Rsa Key</KeyName>
          </KeyInfo>
          <CipherData>
            <CipherValue>odapFFPDF1Fgsk2wyvbwVC4SNISqhWc9lXiAq+I/OW3wVVqBCPowxyen9M7c9+KUBkXmGSfaUVxDMlqutChv6g6VU8h4TWG3W6Tw/istjfw/UYrRsGguPiOqdvRsl9XLBmnS37v99+VX7FEA9TKb6ufC0a3Defp2MNpGTvTIR20=</CipherValue>
          </CipherData>
        </EncryptedKey>
      </KeyInfo>
      <CipherData>
        <CipherValue>lHPPFRJAH2hIm/Ya+ABRMP5mo5rEYwL2aBJQ/DT4Q+1OZXaftutiddxxJZ4LSgw3pzi1QJpU8eOPwFVebvqFVA4cjs27l8Iqz50E/R/tBfS7e2oqdWTRsc8IFfE/xOIieMp22BuFsYEDbgnIbLdbHJnw+92zyt2lUlzJpW9epNpnb29sVQhtNJ9cPjAaYAaU</CipherValue>
      </CipherData>
    </EncryptedData>
  </smtp>
</mailSettings>

My only problem right now is how do I read those values inside my code without having to decrypt and save the config file. I do not want to rewrite the webconfig file ever time I need to read the mail setting section or even the connection string section.

If I have a method like this:

public static string DecryptMailSettings()
{
    var config = WebConfigurationManager.OpenWebConfiguration("~");
    ConfigurationSection section = config.GetSection("system.net/mailSettings/smtp");
    if (section.SectionInformation.IsProtected)
    {
        section.SectionInformation.UnprotectSection();
        return section.???;
    }
    return "Nothing was read";
}

How do I get the value of lets say "host" from the example above.

Related posts

Recent Viewed