Link to home
Start Free TrialLog in
Avatar of ksd123
ksd123

asked on

Encryption /Decryption and Error Log in windows application using c#

Hi All,

We are developing windows form application using .Net framework 2.0 and c# to start/stop a windows service on a remote server using impersonation.

1)How can I encrypt/decrypt App.config entries and retrieve in class file

//App.config file entries

    <add key="DomainUser value="xxxxx"/>
    <add key="DomainPassword" value="yyyyyy"/>
     <add key="DomainName" value="zzzzz"/>    

//Getting App.config entries in cs file
 
                if (LogonUser(ConfigurationManager.AppSettings["DomainUser"].ToString(), ConfigurationManager.AppSettings["DomainName"].ToString(), ConfigurationManager.AppSettings["DomainPassword"].ToString(), LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, ref token))
     
2)How to maintain log information in window application ?

Please suggest me
ASKER CERTIFIED SOLUTION
Avatar of dj_alik
dj_alik

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of hjgode
For 2) Logging I used NSpring Logging in the past. It can log to windowss event logs or to file etc.: http://sourceforge.net/projects/nspring/
In the past I have created the attached code for encrypting and decrytping strings in the config file. It used synchronous encryption and so is not the most secure method possible but it is more than good enough for my purposes.

The code below assumes the existence of two strings "string1" and "string2" being stored in the resources which are the password and salt. You can change this as required.

The advantage of this method is that the encryption is not based on the machine and so can be easily rolled out to numerous machines without issue.

Michael

using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;

namespace Vault.Classes {
   internal static class Vault {
      /************************************************************************************************************************************/
      #region Public Methods

      public static string Encrypt(string plainText) {
         RijndaelManaged key = GetKey();
         byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);
         using (ICryptoTransform encryptor = key.CreateEncryptor()) {
            using (MemoryStream memoryStream = new MemoryStream()) {
               using (CryptoStream cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write)) {
                  cryptoStream.Write(plainTextBytes, 0, plainText.Length);
                  cryptoStream.FlushFinalBlock();
                  return Convert.ToBase64String(memoryStream.ToArray());
               }
            }
         }
      }

      public static string Decrypt(string encryptedString) {
         RijndaelManaged key = GetKey();
         byte[] encryptedData = Convert.FromBase64String(encryptedString);
         using (ICryptoTransform decryptor = key.CreateDecryptor(key.Key, key.IV)) {
            using (MemoryStream memoryStream = new MemoryStream(encryptedData)) {
               using (CryptoStream cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read)) {
                  byte[] plainText = new byte[encryptedData.Length];
                  int decryptedCount = cryptoStream.Read(plainText, 0, plainText.Length);
                  return Encoding.UTF8.GetString(plainText, 0, decryptedCount);
               }
            }
         }
      }

      #endregion
      /************************************************************************************************************************************/
      #region Private Methods

      //Create encryption key
      private static RijndaelManaged GetKey() {
         RijndaelManaged key = new RijndaelManaged();
         byte[] passwordBytes = Encoding.UTF8.GetBytes(Properties.Resources.string1);
         byte[] saltBytes = Encoding.UTF8.GetBytes(Properties.Resources.string2);
         PasswordDeriveBytes p = new PasswordDeriveBytes(passwordBytes, saltBytes);
         key.IV = p.GetBytes(key.BlockSize / 8);
         key.Key = p.GetBytes(key.KeySize / 8);
         return key;
      }

      #endregion
      /************************************************************************************************************************************/
   }
}

Open in new window

Avatar of ksd123
ksd123

ASKER

Hi,

Please suggest me how to maintain event log in windows form application.

Thanks,
Hello

first download and install the nspring for net http://sourceforge.net/projects/nspring/files/?source=navbar.
To use logging to the windows event data first add a reference to the nspring assemblies and then include the nspring logging namespaces:

...
using NSpring.Logging;
using NSpring.Logging.Loggers;
...
        //global logger instance:
        Logger logger = new WindowsEventLogger(System.Reflection.Assembly.GetExecutingAssembly().GetName().Name);
        //you may use different logging levels:
        private Level EventLevel = Level.Info;
        private Level LogLevel = Level.Info;

Open in new window


in your class constructor set the desired logging level:

        public class myClass(string LoggingLevel, string[] LoggingMethodInfo, ...)
        {
            this.LoggingLevel = LoggingLevel;
            LoggingMethod = LoggingMethodInfo;
            ...
                try
                {
                    logger.Open();
                }
                catch
                {
                }
                AddMsg(Level.Verbose, "Creating Socket");
                mySocket = new Socket(myEndpoint.Address.AddressFamily, SocketType.Dgram, ProtocolType.Udp);
...

Open in new window


Now, you can use the logging via AddMsg function:

                AddMsg(Level.Verbose, "Binding Socket");
...
                AddMsg(Level.Verbose, "Starting to Listen");
...
                AddMsg(Level.Info, "Listening for requests on IP address " + myEndpoint.Address.ToString() + " port " + myEndpoint.Port.ToString());
...
                            AddMsg(Level.Debug, "CheckStates Count after " + CurrStates.Count.ToString());
...
        private void AddMsg(Level level, string text)
        {
            if (level >= EventLevel)
                OnTFTPServerEvent(new TFTPServerEventArgs(text));

            if (logger.IsOpen && (level >= LogLevel))
                logger.Log(level, text);
        }

Open in new window


The above has been taken of my tftp service: http://www.hjgode.de/wp/2010/06/09/writing-a-tftp-server-windows-service/

There is a good nspring example at http://www.codeproject.com/Articles/5212/A-Comprehensive-Logging-Package-for-NET
Avatar of ksd123

ASKER

Hi,

As I mentioned earlier  we are developing windows form application using .Net framework 2.0 and c# to start/stop a windows service on a remote server.I have below  piece of code and would like to know how to  maintain logs (machine name,current logon user who started/stopped the service) & also execeptions.

  private void start_Click(object sender, EventArgs e)
        {

            ServiceController sc = new ServiceController("FirstService");
            sc.Start();
            sc.WaitForStatus(System.ServiceProcess.ServiceControllerStatus.Running);
            MessageBox.Show("service started");
            sc.Refresh();
       }

        private void stop_Click(object sender, EventArgs e)
        {
            ServiceController sc = new ServiceController("FirstService");
            sc.Stop();
            sc.WaitForStatus(System.ServiceProcess.ServiceControllerStatus.Stopped);
            MessageBox.Show("Service stooped");
            sc.Refresh();
        }
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of ksd123

ASKER

Thank you all