Programmcodes zu berschiedenen Themen c#

Encrypting/Decrypting

Es gibt viele und professionelle Ver/Entschlüsselungverfahren. Für manche einnfache Anwendungen sind diese Verfahren
etwas überzogen. Der folgende Code zeigt eine Klasse, Trw.Encrypting.cs genannt, die mehere einfache Verfahren kapselt.

Die Klasse enthält ausschließlich static functions, so daß es nicht notwendig wird, erst ein Objekt dieser Klasse zu erzeugen, um die Funktionalität der Klasse zu nutzen.

Es sind folgende Funktion immer paarweise für Encrypting/Decrypting vorhanden:

  • public static void Encrypt(string input, out string output, string key)
    public static void Decrypt(string input, out string output, string key)

  • public static void Encrypt(byte[] input, out byte[] output ,byte key)
    public static void Decrypt(byte[] input, out byte[] output, byte key)

  • public static void Encrypt(string filenameinput, string filenamoutput, byte key)
    public static void Decrypt(string filenameinput,  string filenamoutput, byte key)
  • public static string BytearrayToString(byte[] input)

Hier beginnt die Klasse. Der Code ist getestet und lauffähig, so wie er hier steht. Man kann ihn einfach in einem
c#-Projekt in die Klassendatei Trw.Encrypting.cs kopieren.

Im Anschluß dieser Klassenvorlage befindet sich der Testcode einer Consolenanwendung.

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;

namespace Trw.Easyencrypting
{
    /// <summary>
    /// this class encapsulates a simple Encrypting/Decrypting-algorithmus
    /// </summary>
    class Encrypting
    {
        private static byte _key = 21;
        private static string _strkey = "TRWAschau";
        /// <summary>
        /// this function return the input string as an encrypted string in output
        /// key must not be null but may be an empty string
        /// Use the same key for encrypting and decrypting, otherwise you'll not succed 
        /// It's a good idea using the internal key
        /// </summary>
        /// <param name="input">string that is to be encrypted</param>
        /// <param name="output">string where the encrypted string goes to</param>
        /// <param name="key">if key is an empty string an internal key is used</param>
        public static void Encrypt(string input, out string output, string key)
        {
           long cptZahl;
           string cptString = string.Empty;
           int position = 0;
           byte[] kkeyZahl, korgZahl;
           output = string.Empty;

            if (key == null)
                throw new Exception("key must not be null but can be an empty string");
            string tempkey = key;
            //use the internal key
            if (tempkey == string.Empty)
                tempkey = Encrypting._strkey;
            if (input == null)
                throw new Exception("the string you want to be encrypted must not be null");
            int len = input.Length;
            if (len <= 0)
                throw new Exception("Encrypting an empty string makes no sense !");

            for (int i = 0;   i < len; i++)
            {
               
                if (position > tempkey.Length-1)
                    position =0;
                kkeyZahl = ASCIIEncoding.ASCII.GetBytes(tempkey.Substring(position,1));
                //Verschlüsseln
                string substr = input.Substring(i, 1);
                korgZahl = ASCIIEncoding.ASCII.GetBytes(input.Substring(i,1));
                cptZahl =( (long)korgZahl[0]) ^ ((long)kkeyZahl[0]);
                int ii = (int)cptZahl / 16;
                char cc;
                if (ii > 9)
                {
                    cc = (char)(65 + (ii - 10));
                    cptString = cc.ToString();
                }
                else
                {
                    cptString = ii.ToString();
                }
                int ii1 = (int)cptZahl % 16;
                if (ii1 > 9)
                {
                    cc = (char)(65 + (ii1 - 10));
                    cptString += cc.ToString();
                }
                else
                {
                    cptString += ii1.ToString();
                }
                if (cptString.Length < 2)
                    cptString = "0" + cptString;
                output += cptString;
                position++;
            }
        }
        /// <summary>
        /// this function return the encrypted input string as an decrypted string in output
        /// key must not be null but may be an empty string
        /// Use the same key for encrypting and decrypting, otherwise you'll not succed 
        /// It's a good idea using the internal key
        /// </summary>
        /// <param name="input">string that is to be decrypted</param>
        /// <param name="output">string where the decrypted string goes to</param>
        /// <param name="key">if key is an empty string an internal key is used</param>
        public static void Decrypt(string input, out string output, string key)
        {
            long  orgZahl;
            string cptString = string.Empty;
            int position = 0;
            byte[] kkeyZahl, kcptZahl,korgZahl = {0};
            output = string.Empty;

            if (key == null)
                throw new Exception("key must not be null but can be an empty string");
            string tempkey = key;
            //use the internal key
            if (tempkey == string.Empty)
                tempkey = Encrypting._strkey;
            if (input == null)
                throw new Exception("the string you want to be encrypted must not be null");
            int len = input.Length;
            if (len <= 0)
                throw new Exception("Encrypting an empty string makes no sense !");

            for (int i = 0; i < len; i++)
            {
                if (position > tempkey.Length - 1)
                    position = 0;
                kkeyZahl = ASCIIEncoding.ASCII.GetBytes(tempkey.Substring(position, 1));
                if (i > input.Length / 2 -1)
                    break;
                cptString = input.Substring(i * 2, 2);
                string str = cptString.Substring(0, 1);
                string str1 = cptString.Substring(1, 1);
                int ii = 0;
                int ii1 = 0;
                if ((str.CompareTo("0") > 0 || str.Equals( "0")) && (str.CompareTo("9") < 0 || str.Equals( "9")))
                {
                     ii = int.Parse(str) * 16;
                }
                else if ((str.CompareTo("A") > 0 || str.Equals("A")) && (str.CompareTo("F") < 0 || str.Equals("F")))
                {
                    byte[] bar = ASCIIEncoding.ASCII.GetBytes(str1);
                    if (bar[0] >= 65 && bar[0] <= 70)
                        ii1 = (int)(bar[0] - 65 + 10);
                }
                if ((str1.CompareTo("0") > 0 || str1.Equals("0")) && (str1.CompareTo("9") < 0 || str1.Equals("9")))
                {
                     ii1 = int.Parse(str1);
                        }
                else if ((str1.CompareTo("A") > 0 || str1.Equals("A")) && ( str1.CompareTo("F") < 0 || str1.Equals("F")))
                {
                    byte[] bar = ASCIIEncoding.ASCII.GetBytes(str1);
                    if ((bar[0] >= 65) && (bar[0] <= 70))
                        ii1 = (int)(bar[0] - 65 + 10);
                }
                byte bb = (byte)( ii + ii1);
               korgZahl[0] =(byte)( bb ^ kkeyZahl[0]);
               output += ASCIIEncoding.ASCII.GetString(korgZahl);
               position++;
            }
        }
 
        /// <summary>
        /// Encrypting the value of  input and returns it in output.
        /// If key == 0 an internal class key is used.
        /// Throws an exception in case of a fault.
        /// </summary>
        /// <param name="input"></param>
        /// <param name="output"></param>
        /// <param name="key"></param>
        public static void Encrypt(byte[] input, out byte[] output ,byte key)
        {
            byte tempkey = key;
            if (tempkey == 0)
                tempkey = Encrypting._key;
            if (input == null)
                throw new Exception("make the input array != null");
            int len = input.Length;
            if (len <= 0)
                throw new Exception("object(input) to be encrypted is empty");
            if (tempkey > 128 || tempkey <= 0)
                throw new Exception("key has to be in range 1 to 128");
            output = new byte[len];
            for (int i = 0; i < len; i++)
            {
                output[i] = (byte)((input[i] + tempkey)%255);
            }
        }
        /// <summary>
        /// Decrypting the value of  input and returns it in output.
        /// If key == 0 an internal class key is used.
        /// Throws an exception in case of a fault.
        /// </summary>
        /// <param name="input"></param>
        /// <param name="output"></param>
        /// <param name="key"></param>
        public static void Decrypt(byte[] input, out byte[] output, byte key)
        {
            byte tempkey = key;
            if (tempkey == 0)
                tempkey = Encrypting._key;
            if (input == null)
                throw new Exception("make the input array != null");
            int len = input.Length;
            if (len <= 0)
                throw new Exception("object(input) to be encrypted is empty");
            if (tempkey > 128 || tempkey <= 0)
                throw new Exception("key has to be in range 1 to 128");
            output = new byte[len];
            for (int i = 0; i < len; i++)
            {
                output[i] = (byte)((input[i] - tempkey)%255);
            }
        }
        /// <summary>
        /// Encrypting the input file (filenameinput)  and returns it in output file (filenamoutput).
        /// If key == 0 an internal class key is used.
        /// Please notice! filenameinput and filenamoutput must consist of the full path
        /// Throws an exception in case of a fault.
        /// </summary>
        /// <param name="filenameinput">filename of file to be encrypted</param>
        /// <param name="filenamoutput">filename of file this encrypted bytes go to</param>
        /// <param name="key">if key == 0 an internal class key is used</param>
        public static void Encrypt(string filenameinput, string filenamoutput, byte key)
        {
            FileStream inputstream = null;
            FileStream outputstream = null;
            byte tempkey = key;
           if (tempkey == 0)
                tempkey = Encrypting._key;
            if (filenameinput == null)
                throw new Exception("filenameobject is null");
            if (!File.Exists(filenameinput))
                throw new Exception("input file does not exist!");
            try
            {
                if (!File.Exists(filenamoutput))
                {
                    outputstream = File.Create(filenamoutput);
                }
                else{
                    outputstream = File.OpenWrite(filenamoutput);
                }
                    inputstream = File.Open(filenameinput, FileMode.Open, FileAccess.Read);
                if (outputstream == null || inputstream == null)
                    throw new Exception("input file or output file could not be open!");
                byte bb = 0;
                int i = 0;
                try
                {
                    while (i < inputstream.Length)
                    {
                        bb = (byte)inputstream.ReadByte();
                        bb = (byte)((bb + tempkey) % 255);
                        outputstream.WriteByte(bb);
                        i++;
                    }
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
            catch (IOException ex)
            {
                throw ex;
            }
            finally
            {
                inputstream.Close();
                outputstream.Close();
            }
        }
        /// <summary>
        /// Decrypting the input file (filenameinput)  and returns it in output file (filenamoutput).
        /// If key == 0 an internal class key is used.
        /// Please notice! filenameinput and filenamoutput must consist of  full path
        /// Throws an exception in case of a fault.
        /// </summary>
        /// <param name="filenameinput">filename of file to be decrypted</param>
        /// <param name="filenamoutput">filename of file this decrypted bytes go to</param>
        /// <param name="key">if key == 0 an internal class key is used</param>
        public static void Decrypt(string filenameinput,  string filenamoutput, byte key)
        {
            FileStream inputstream = null;
            FileStream outputstream = null;
            byte tempkey = key;
           if (tempkey == 0)
                tempkey = Encrypting._key;
            if (filenameinput == null)
                throw new Exception("filenameobject is null");
            if (!File.Exists(filenameinput))
                throw new Exception("input file does not exist!");
            try
            {
                if (!File.Exists(filenamoutput))
                {
                    outputstream = File.Create(filenamoutput);
                }
                else{
                    outputstream = File.OpenWrite(filenamoutput);
                }
                inputstream = File.Open(filenameinput, FileMode.Open, FileAccess.Read);
                if (outputstream == null || inputstream == null)
                    throw new Exception("input file or output file could not be open!");
                byte bb;
                int i = 0;
                try
                {
                    while (i < inputstream.Length)
                    {
                        bb = (byte)inputstream.ReadByte();
                        bb = (byte)((bb - tempkey) % 255);
                        outputstream.WriteByte(bb);
                        i++;
                    }
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
                catch (IOException ex)
                {
                    throw ex;
                }
                finally
                {
                    inputstream.Close();
                    outputstream.Close();
                }
        }

        /// <summary>
        /// Converts a bytearray to an appropriate string.
        /// Throws an exception in case of a fault.
        ///  </summary>
        /// <param name="input">byte array that is to convert to a string</param>
        /// <returns>return value as string</returns>
        public static string BytearrayToString(byte[] input)
        {
            if (input == null)
                throw new Exception("make the input array != null");
            int len = input.Length;
            if (len <= 0)
                throw new Exception("object to be converted is empty");
            return ASCIIEncoding.ASCII.GetString(input); ;
        }
        /// <summary>
        /// Convert a string to an appropriate byte array.
        /// Throws an exception in case of a fault.
        /// </summary>
        /// <param name="input">string object is to convert</param>
        /// <returns>retrun value is a byte array</returns>
        public static byte[] StringToBytearray( string input)
        {
            if (input == null)
                throw new Exception("make the input array != null");
            int len = input.Length;
            if (len <= 0)
                throw new Exception("object to be converted is empty");
            return ASCIIEncoding.ASCII.GetBytes(input); ;
        }
    }
}

========================================================================================
                      Consolenanwendung zum Testen der obigen Klassenvorlage.
=============================================================================

Wenn man eine Standardkonsolenanwendung erzeugt hat, kopiert man diesen untenstehenden Code in die Datei
Program.cs, sofern man sie nicht umbenannt hat.

Um Namensraumkonflikte oder zusätzliche Verweise zu vermeiden, sollten sich Program.cs und Trw.Encrypting.cs
im selben Folder befinden.
Wenn man das beachtet, sollte bei Ausprobieren kein Problem auftreten.

using System;
using System.Collections.Generic;
using System.Text;
using Trw.Easyencrypting;


namespace Easyencrypting
{
    class Program
    {
        static void Main(string[] args)
        {
            string str = "Peggy121176";
            Console.WriteLine("Zu verschlüsseln: {0}", str);
            byte[] inp = null;
            //convert string to byte array
            try
            {
                inp = Encrypting.StringToBytearray(str);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Console.ReadLine();
                return;
            }
            byte[] outp = null;
            try
            {
                Encrypting.Encrypt(inp, out outp, 0);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Console.ReadLine();
                return;
            }
            byte[] outp2 = null;
            Console.WriteLine("Verschlüsselt: {0}", ASCIIEncoding.ASCII.GetString(outp));
            string retstr = string.Empty; 
            try
            {
                Encrypting.Decrypt(outp, out outp2, 0);
                retstr = Encrypting.BytearrayToString(outp2);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Console.ReadLine();
                return;
            }
            Console.WriteLine("Entschlüsselt: {0}", retstr);
            Console.ReadLine();

            try
            {
                Encrypting.Encrypt(@"C:\testencrypting.txt", @"C:\testencrypted.txt", 31);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            try

            {
                Encrypting.Decrypt(@"C:\testencrypted.txt", @"C:\testdecrypted.txt", 31);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

            Console.WriteLine();
            Console.WriteLine("_______________________________________________");
            Console.WriteLine("Use of string encrypting and decrypting");

            string outputstr = string.Empty ;
            string input = "sondermayer Paul";
            try
            {
                Encrypting.Encrypt(input, out outputstr, "");
                Console.WriteLine();
                Console.WriteLine(input);
                Console.WriteLine(outputstr);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            string outputstr2 = string.Empty;
            try
            {
                Encrypting.Decrypt(outputstr, out outputstr2, "");
                Console.WriteLine();
                Console.WriteLine(outputstr);
                Console.WriteLine(outputstr2);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

            Console.WriteLine("Fertig");
            Console.ReadLine();
      
        }
    }

VIEL SPASS