Avatar of fwsteal
fwsteal
 asked on

asp.net 2 c# encrypt/decrypt in class file

What I have is a aspx file that encrypts and decrypts the webconfig file. It works fine, but I'd like to put it into a class file and I'm not sure
how to do it.

-------------
admin/securewebconfig.aspx contents:
 <asp:Label ID="Label1" runat="server"></asp:Label>
 <br />
 <asp:Button ID="ButtonProtect" runat="server" Text="Encrypt" OnClick="ButtonProtect_Click" />
 <asp:Button ID="ButtonUnProtect" runat="server" Text="Decrypt" OnClick="ButtonUnProtect_Click" />
 <br />
 <asp:Label ID="LabelMessage" runat="server"></asp:Label>
-------------

admin/securewebconfig.aspx.cs contents:
 protected void Page_Load(object sender, EventArgs e)
  {
   LabelMessage.Text = "";
   LabelMessage.Visible = false;
   Label1.Text = "In order to secure the Web.Config, please select either of the following buttons:";
  }

 protected void ButtonProtect_Click(object sender, EventArgs e)
  {
   ProtectSection("connectionStrings", "RSAProtectedConfigurationProvider");
   //Utilities.EncryptWebConfig("connectionStrings", "RSAProtectedConfigurationProvider"); //what I'd like to do
  }

 protected void ButtonUnProtect_Click(object sender, EventArgs e)
  {
   UnProtectSection("connectionStrings");
   //Utilities.DeEncryptWebConfig("connectionStrings"); //what I'd like to do
  }

 private void ProtectSection(string sectionName, string provider)
  {
   Configuration config = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);
   ConfigurationSection section = config.GetSection(sectionName);
   if (section != null && !section.SectionInformation.IsProtected)
    {
     try
      {
       section.SectionInformation.ProtectSection(provider);
       config.Save();
       LabelMessage.Visible = true;
       LabelMessage.Text = "The webconfig is protected by the means of encryption throught the RSAProtectedConfigurationProvider.";
      }
     catch (Exception ex)
      {
       LabelMessage.Visible = true;
       LabelMessage.Text = ex.ToString();
       LabelMessage.Text += "<br /> <br />The ASP.NET process account (either the local ASPNET or Network Service account, by default) ";
       LabelMessage.Text += "must have write permission granted for the Web.config file.";
      }
    }
   else
    {
     LabelMessage.Visible = true;
     LabelMessage.Text = "Sorry there was an error meeting your request.";
    }
  }

 private void UnProtectSection(string sectionName)
  {
   Configuration config = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);
   ConfigurationSection section = config.GetSection(sectionName);
   if (section != null && section.SectionInformation.IsProtected)
    {
     try
      {
       section.SectionInformation.UnprotectSection();
       config.Save();
       LabelMessage.Visible = true;
       LabelMessage.Text = "The webconfig is unprotected and is no longer encrypted.";
      }
     catch (Exception ex)
      {
       LabelMessage.Visible = true;
       LabelMessage.Text = ex.ToString();
       LabelMessage.Text += "<br /> <br />The ASP.NET process account (either the local ASPNET or Network Service account, by default) ";
       LabelMessage.Text += "must have write permission granted for the Web.config file.";
      }
    }
   else
    {
     LabelMessage.Visible = true;
     LabelMessage.Text = "Sorry there was an error meeting your request.";
    }
  }
-------------

app_code/bll/clsUtilities.cs contents:
public static class Utilities
 {
  static Utilities()
   {
    // TODO: Add constructor logic here
   }

  public static string EncryptWebConfig(String connectionStrings, string RSAProtectedConfigurationProvider) //not sure if this is correct
   {
    //?
   }
 
  public static string DeEncryptWebConfig(String connectionStrings) //not sure if this is correct
   {
    //?
   }
ASP.NET

Avatar of undefined
Last Comment
fwsteal

8/22/2022 - Mon
nauman_ahmed

public static class Utilities
 {
  static Utilities()
   {
    // TODO: Add constructor logic here
   }

  private void ProtectSection(string sectionName, string provider)
  {
   Configuration config = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);
   ConfigurationSection section = config.GetSection(sectionName);
   if (section != null && !section.SectionInformation.IsProtected)
    {
     try
      {
       section.SectionInformation.ProtectSection(provider);
       config.Save();
       LabelMessage.Visible = true;
       LabelMessage.Text = "The webconfig is protected by the means of encryption throught the RSAProtectedConfigurationProvider.";
      }
     catch (Exception ex)
      {
       LabelMessage.Visible = true;
       LabelMessage.Text = ex.ToString();
       LabelMessage.Text += "<br /> <br />The ASP.NET process account (either the local ASPNET or Network Service account, by default) ";
       LabelMessage.Text += "must have write permission granted for the Web.config file.";
      }
    }
   else
    {
     LabelMessage.Visible = true;
     LabelMessage.Text = "Sorry there was an error meeting your request.";
    }
  }
 
 private void UnProtectSection(string sectionName)
  {
   Configuration config = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);
   ConfigurationSection section = config.GetSection(sectionName);
   if (section != null && section.SectionInformation.IsProtected)
    {
     try
      {
       section.SectionInformation.UnprotectSection();
       config.Save();
       LabelMessage.Visible = true;
       LabelMessage.Text = "The webconfig is unprotected and is no longer encrypted.";
      }
     catch (Exception ex)
      {
       LabelMessage.Visible = true;
       LabelMessage.Text = ex.ToString();
       LabelMessage.Text += "<br /> <br />The ASP.NET process account (either the local ASPNET or Network Service account, by default) ";
       LabelMessage.Text += "must have write permission granted for the Web.config file.";
      }
    }
   else
    {
     LabelMessage.Visible = true;
     LabelMessage.Text = "Sorry there was an error meeting your request.";
    }
  }

Then from your any ASPX.CS page you can call the methods like:

Utilities.ProtectSection() or Utilities.UnProtectSection()

--Nauman.
fwsteal

ASKER

aspx file -
1. how will it know what to populate in the LabelMessage control?
2. under utilities. protectsection and unprotectsection were not available in the intellisense

    protected void ButtonProtect_Click(object sender, EventArgs e)
    {
        Utilities.ProtectSection("connectionStrings", "RSAProtectedConfigurationProvider");
    }


    protected void ButtonUnProtect_Click(object sender, EventArgs e)
    {
        Utilities.UnProtectSection("connectionStrings");
    }
------------------------

class file
1. Error 1 'ProtectSection': cannot declare instance members in a static class
2. Error 2 'UnProtectSection': cannot declare instance members in a static class
3. how will the LabelMessage be returned?
nauman_ahmed

woops:


public static string ProtectSection(string sectionName, string provider)
{
 ConfigurationSection section = config.GetSection(sectionName);
   if (section != null && !section.SectionInformation.IsProtected)
    {
     try
      {
       section.SectionInformation.ProtectSection(provider);
       config.Save();
       return("The webconfig is protected by the means of encryption throught the RSAProtectedConfigurationProvider.");
      }
     catch (Exception ex)
      {
       return("The ASP.NET process account (either the local ASPNET or Network Service account, by default must have write permission granted for the Web.config file.");
      }
    }
   else
    {
     return("Sorry there was an error meeting your request.");
    }

}

public static string UnProtectSection(string sectionName)
{
  Configuration config = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);
   ConfigurationSection section = config.GetSection(sectionName);
   if (section != null && section.SectionInformation.IsProtected)
    {
     try
      {
       section.SectionInformation.UnprotectSection();
       config.Save();
       return("The webconfig is unprotected and is no longer encrypted.");
      }
     catch (Exception ex)
      {
       return("The ASP.NET process account (either the local ASPNET or Network Service account, by default must have write permission granted for the Web.config file.");
      }
    }
   else
    {
     return("Sorry there was an error meeting your request.");
    }

}

HTH, Nauman.
Your help has saved me hundreds of hours of internet surfing.
fblack61
fwsteal

ASKER
HTH, Nauman,

Errors:

1. Error 1 The name 'config' does not exist in the current context
  ConfigurationSection section = config.GetSection(sectionName);
  config.Save();

2. Error 2 The name 'Request' does not exist in the current context
  Configuration config = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);

So I added the following directives:
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Data.Common;
using System.IO;
using System.Net.Mail;
using System.Web;
using System.Web.Configuration;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

Yet, still no luck.
fwsteal

ASKER
oh, i updaed the aspx file:

    protected void ButtonProtect_Click(object sender, EventArgs e)
    {
        LabelMessage.Visible = true;
        LabelMessage.Text = Utilities.ProtectSection("connectionStrings", "RSAProtectedConfigurationProvider");
    }


    protected void ButtonUnProtect_Click(object sender, EventArgs e)
    {
        LabelMessage.Visible = true;
        LabelMessage.Text = Utilities.UnProtectSection("connectionStrings");
    }
nauman_ahmed

Change the class declaration to the following:

public static class Utilities : Page
 {
  static Utilities()
   {
    // TODO: Add constructor logic here
   }

For request just use HttpContext.Current.Request. Let me know if it works. It would be even better if you change


public static string UnProtectSection(string sectionName)
{
}

to

public static string UnProtectSection(string sectionName, string ApplicationPath)
{

}

and pass the path to application as a string.

--Nauman.
Get an unlimited membership to EE for less than $4 a week.
Unlimited question asking, solutions, articles and more.
fwsteal

ASKER
how do i pass the path to application as a string from the aspx file?
nauman_ahmed

using Request.ApplicationPath :)

--Nauman.
fwsteal

ASKER
so would it be something like:

LabelMessage.Text = Utilities.UnProtectSection(Request.ApplicationPath("connectionStrings"));
Experts Exchange is like having an extremely knowledgeable team sitting and waiting for your call. Couldn't do my job half as well as I do without it!
James Murphy
nauman_ahmed

All you need to do is Request.ApplicationPath and it will return the application path. Request.ApplicationPath do not accept any parameters.

--Nauman.
fwsteal

ASKER
okay.


1. Error 1 Static class 'Utilities' cannot derive from type 'System.Web.UI.Page'. Static classes must derive from object.

    public static class Utilities : Page

So I dropped the : Page to
   public static class Utilities

and now I'm back to the error with: The name 'config' does not exist in the current context



Here is the change to use request.apppath
Configuration config = WebConfigurationManager.OpenWebConfiguration(HttpContext.Current.Request.ApplicationPath);
nauman_ahmed

ooh man... :) try the following

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Data.Common;
using System.IO;
using System.Net.Mail;
using System.Web;
using System.Web.Configuration;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public class Utilities : Page
      {
            public Utilities()
            {
                  //
                  // TODO: Add constructor logic here
                  //
            }

            public static string ProtectSection(string sectionName, string provider)
            {
                  ConfigurationSection section = config.GetSection(sectionName);
                  if (section != null && !section.SectionInformation.IsProtected)
                  {
                        try
                        {
                              section.SectionInformation.ProtectSection(provider);
                              config.Save();
                              return("The webconfig is protected by the means of encryption throught the RSAProtectedConfigurationProvider.");
                        }
                        catch (Exception ex)
                        {
                              return("The ASP.NET process account (either the local ASPNET or Network Service account, by default must have write permission granted for the Web.config file.");
                        }
                  }
                  else
                  {
                        return("Sorry there was an error meeting your request.");
                  }

            }

            public static string UnProtectSection(string sectionName,string AppPath)
            {
                  Configuration config = WebConfigurationManager.OpenWebConfiguration(AppPath);
                  ConfigurationSection section = config.GetSection(sectionName);
                  if (section != null && section.SectionInformation.IsProtected)
                  {
                        try
                        {
                              section.SectionInformation.UnprotectSection();
                              config.Save();
                              return("The webconfig is unprotected and is no longer encrypted.");
                        }
                        catch (Exception ex)
                        {
                              return("The ASP.NET process account (either the local ASPNET or Network Service account, by default must have write permission granted for the Web.config file.");
                        }
                  }
                  else
                  {
                        return("Sorry there was an error meeting your request.");
                  }

            }



      }

--Nauman.
Get an unlimited membership to EE for less than $4 a week.
Unlimited question asking, solutions, articles and more.
fwsteal

ASKER
Below is the entire class file. I still get errors with config.

Error 1 The name 'config' does not exist in the current context.
 ConfigurationSection section = config.GetSection(sectionName);

Error 2 The name 'config' does not exist in the current context.
 config.Save();



---------------------------
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Data.Common;
using System.IO;
using System.Net.Mail;
using System.Web;
using System.Web.Configuration;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

/// <summary>
/// Class contains miscellaneous functionality
/// </summary>


public class Utilities : Page
{
    public Utilities()
    {
        //
        // TODO: Add constructor logic here
        //
    }

    public static string ProtectSection(string sectionName, string provider)
    {
        ConfigurationSection section = config.GetSection(sectionName);
        if (section != null && !section.SectionInformation.IsProtected)
        {
            try
            {
                section.SectionInformation.ProtectSection(provider);
                config.Save();
                return ("The webconfig is protected by the means of encryption throught the RSAProtectedConfigurationProvider.");
            }
            catch (Exception ex)
            {
                return ("The ASP.NET process account must have write permission granted for the Web.config file.");
            }
        }
        else
        {
            return ("Sorry there was an error meeting your request.");
        }

    }

    public static string UnProtectSection(string sectionName, string AppPath)
    {
        Configuration config = WebConfigurationManager.OpenWebConfiguration(AppPath);
        ConfigurationSection section = config.GetSection(sectionName);
        if (section != null && section.SectionInformation.IsProtected)
        {
            try
            {
                section.SectionInformation.UnprotectSection();
                config.Save();
                return ("The webconfig is unprotected and is no longer encrypted.");
            }
            catch (Exception ex)
            {
                return ("The ASP.NET process account must have write permission granted for the Web.config file.");
            }
        }
        else
        {
            return ("Sorry there was an error meeting your request.");
        }

    }


    #region "Mail"
    // Generic method for sending emails
    public static void SendMail(string from, string to, string subject, string body)
    {
        // Configure mail client (may need additional code for authenticated SMTP servers)
        SmtpClient mailClient = new SmtpClient(siteConfiguration.MailServer);
        // Create the mail message
        MailMessage mailMessage = new MailMessage(from, to, subject, body);
        /*
           // For SMTP servers that require authentication
           message.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate", 1);
           message.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusername", "SmtpHostUserName");
           message.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendpassword", "SmtpHostPassword");
          */
        // Send mail
        mailClient.Send(mailMessage);
    }
    #endregion


    #region "LogError"
    // Send error log mail
    public static void LogError(Exception ex)
    {
        // get the current date and time
        string dateTime = DateTime.Now.ToLongDateString() + ", at "
                        + DateTime.Now.ToShortTimeString();
        // stores the error message
        string errorMessage = "Exception generated on " + dateTime;
        // obtain the page that generated the error
        System.Web.HttpContext context = System.Web.HttpContext.Current;
        errorMessage += "\n\n Page location: " + context.Request.RawUrl;
        // build the error message
        errorMessage += "\n\n Message: " + ex.Message;
        errorMessage += "\n\n Source: " + ex.Source;
        errorMessage += "\n\n Method: " + ex.TargetSite;
        errorMessage += "\n\n Stack Trace: \n\n" + ex.StackTrace;
        // send error email in case the option is activated in Web.Config
        if (siteConfiguration.EnableErrorLogEmail)
        {
            string from = "it.support";
            string to = siteConfiguration.ErrorLogEmail;
            string subject = siteConfiguration.SiteName + " error report";
            string body = errorMessage;
            SendMail(from, to, subject, body);
        }
    }
    #endregion


    #region "AdminMenuReader"
    //read the contents of the admin directory and create a data table
    //only display asp.net files but not the default file
    public static DataTable AdminMenuReader()
    {
        FileInfo fi = new FileInfo(HttpContext.Current.Server.MapPath("admin")); //fi.DirectoryName
        DirectoryInfo di = fi.Directory;
        FileSystemInfo[] fsi = di.GetFiles(); //di.FullName returns the full path
        DataTable dt = new DataTable();
        dt.Columns.Add(new DataColumn("Name"));
        dt.Columns.Add(new DataColumn("Path"));
        foreach (FileSystemInfo info in fsi)
        {
            if (info.Extension == ".aspx" && info.Name != "Default.aspx")
            {
                DataRow row = dt.NewRow();
                row[0] = ProperCase(info.Name);
                row[1] = "../admin/" + info.Name;
                dt.Rows.Add(row);
            }
        }
        return dt;
    }

    //formatter - upper case and drop file extension
    public static string ProperCase(string Input)
    {
        char[] trimChars = { '.', 'a', 's', 'p', 'x' };
        return System.Threading.Thread.CurrentThread.
               CurrentCulture.TextInfo.ToTitleCase(Input.TrimEnd(trimChars));
    }
    #endregion
}
-------------------

any ideas why config keeps blowing up?
ASKER CERTIFIED SOLUTION
nauman_ahmed

Log in or sign up to see answer
Become an EE member today7-DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform
Sign up - Free for 7 days
or
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.
Not exactly the question you had in mind?
Sign up for an EE membership and get your own personalized solution. With an EE membership, you can ask unlimited troubleshooting, research, or opinion questions.
ask a question
fwsteal

ASKER
final working version after some more tweaking:

    protected void ButtonProtect_Click(object sender, EventArgs e)
    {
        LabelMessage.Visible = true;
        LabelMessage.Text = Utilities.ProtectSection("connectionStrings", "RSAProtectedConfigurationProvider", Request.ApplicationPath);
    }


    protected void ButtonUnProtect_Click(object sender, EventArgs e)
    {
        LabelMessage.Visible = true;
        LabelMessage.Text = Utilities.UnProtectSection("connectionStrings", Request.ApplicationPath);
    }
------------

    public static string ProtectSection(string sectionName, string provider, string AppPath)
    {
        Configuration config = WebConfigurationManager.OpenWebConfiguration(AppPath);
        ConfigurationSection section = config.GetSection(sectionName);
        if (section != null && !section.SectionInformation.IsProtected)
        {
            try
            {
                section.SectionInformation.ProtectSection(provider);
                config.Save();
                return ("The webconfig is protected by the means of encryption throught the RSAProtectedConfigurationProvider.");
            }
            catch (Exception ex)
            {
                return ("The ASP.NET process account must have write permission granted for the Web.config file.");
            }
        }
        else
        {
            return ("Sorry there was an error meeting your request.");
        }

    }


      public static string UnProtectSection(string sectionName, string AppPath)
    {
        Configuration config = WebConfigurationManager.OpenWebConfiguration(AppPath);
        ConfigurationSection section = config.GetSection(sectionName);
        if (section != null && section.SectionInformation.IsProtected)
        {
            try
            {
                section.SectionInformation.UnprotectSection();
                config.Save();
                return ("The webconfig is unprotected and is no longer encrypted.");
            }
            catch (Exception ex)
            {
                return ("The ASP.NET process account must have write permission granted for the Web.config file.");
            }
        }
        else
        {
            return ("Sorry there was an error meeting your request.");
        }

    }
nauman_ahmed

Any error this time? :p

--Nauman.
All of life is about relationships, and EE has made a viirtual community a real community. It lifts everyone's boat
William Peck
fwsteal

ASKER
no; thanks for your help :)