Simple XOR Text Encryption and Decryption in Visual C#

Jan 8, 2012 04:30 PM

For this particular example, I will be working on Wndows (sorry X users). I might write a similar guide once I am more comfortable with programming in Linux.

What You Will Need

  • Visual C# 2010 Express (Get it here)
  • Pirate Metal
  • Source Code (For when you are done with the guide.This is not an invitation to skip what's written below. :P ) 

OK, so the second one is optional...

Let's Create a New Project!

Fire up Visual C# Express and start a new console application project. You will end up with a fresh program which looks like this:

So, lets begin writing.

Before anything, insert 3-4 lines in between ''Class Program { '' and ''Static void main..." so it looks like the below image:

The Encryption Function

We will replace the ''Using'' clauses with what's below:

using System;

using System.Collections.Generic;

using System.Collections;

using System.Linq;

using System.Text;

using System.IO;

using System.Diagnostics;

Now where you inserted empty lines, we will declare a new function.

public static string EncryptDecrypt(string textToEncrypt, int encryptionKey)

{

}

Inside of it, we will write the following lines:

StringBuilder inSb = new StringBuilder(textToEncrypt);

            StringBuilder outSb = new StringBuilder(textToEncrypt.Length);

            char c;

            for (int i = 0; i < textToEncrypt.Length; i++)

            {

                c = inSb[i];

                c = (char)(c ^ encryptionKey);

                outSb.Append(c);

            }

            return outSb.ToString();

In short, this function will create two strings, one which will be of the same length of the files which we will encrypt, and the other is set to have no more capacity than the original string.

The function then substitutes the characters in the first string by taking characters one at a time and bringing them to the power of the encryption key. They then get placed in the second string. This is more or less the gist of it.

Your current program should look like so:

Building the Main Program

The main program will utilise our encryptor/decryptor function, array lists and read/write streams. The logic behind this is to pass the location of the file we want to encrypt to the program, then specify where we want the output to go, and give the program our desired encryption key. It will do the rest by opening the original file, reading it line by line, and adding those lines to an array list.

It will then proceed to encrypt the lines in the array list, one by one, and place them into a second array list, which will then be written into our output file and FINALLY, open that output file in windows Notepad.

The script for this is below. It needs to go into the -   "static void Main" function.

ArrayList openArray = new ArrayList();

            ArrayList closeArray = new ArrayList();

            Console.WriteLine("+----------------------+");

            Console.WriteLine("+  ------------------  +");

            Console.WriteLine("+  Encryption Program  +");

            Console.WriteLine("+  ------------------  +");

            Console.WriteLine("+----------------------+");

            Console.WriteLine("");

            Console.WriteLine("");

            Console.WriteLine("Enter the path of the file to be encrypted/decrypted...");

            string beginPath = Console.ReadLine(); //Variable which holds the original file's location.

            Console.WriteLine("Enter the path of the output file.");

            string endPath = Console.ReadLine(); //Variable which holds the output file's location.

            Console.WriteLine("Enter a encryption key. No letters or special characters, only numbers.");

            int enKey = Convert.ToInt32(Console.ReadLine()); //Variable which holds the encryption key.

//==========================OPEN FILE FUNCTION====================================

//Adds healthy lines to the first array.

            using (FileStream fs = new FileStream(beginPath, FileMode.Open, FileAccess.Read))

            {

                using (StreamReader sr = new StreamReader(fs))

                {

                    while (!sr.EndOfStream)

                    {

                        openArray.Add(sr.ReadLine());

                    }

                    sr.Close();

                }

                fs.Close();

            }

            //==========================END OPEN FILE FUNCTION================================

//==========================Encrypt and add to second array=======================

            foreach (string line2 in openArray)

            {

                closeArray.Add(EncryptDecrypt(line2, enKey));

            }

//==========================END Encrypt and add to second array===================

//==========================Save Encrypted Array To File==========================

            TextWriter tw = new StreamWriter(endPath);

            foreach (string encoded in closeArray)

            {

                tw.WriteLine(encoded);

            }

            tw.Close();

//=======================END Save Encrypted Array To File=========================

//========================== Notify and Launch Notepad  ==========================

            Console.WriteLine("Encoding finished.");

            Console.WriteLine("Opening output file now...");

            Process.Start("notepad.exe",endPath);

//========================== END Notify and Launch Notepad  ======================

That's it! We're done. All you have to do now is to compile the program and test it out.

Note: Encryption and Decryption is done in a similar manner. For example, if you encrypt bob.txt and output as bobby.txt and use 666 as the key, then to decrypt, you must reverse the order.

Open - bobby.txt

Output - bob2.txt

Key - 666

Le End.

Comments

No Comments Exist

Be the first, drop a comment!