An Encryption Tool: Slice Up

Introduction

As a general user I have never come across a security tool to encrypt my data except Bit Locker in Windows. Unfortunately, Bit Locker never worked for me. Though, we have compression tools like WinZip or WinRAR that actually compress the data. In fact, what they do is different from encryption/decryption.

You have many third-party solutions to do it. And the most popular one is TrueCrypt.

So, today we will make that kind of software/tool to do those odd jobs.



So, prepare yourself to create a look-alike tool.

Background

In background knowledge we need a basic C# idea and a few .NET framework classes.

So, I must say it is a Beginner Level Project.

Let us look up in Solution Explorer.



In this project, we have two forms (named MainForm and Settings). Additionally, we have a Resource folder that actually holds an image file and icons used in the project.

There is a back-end class that does the actual job of the project (or, I declare the class as "KERNEL").

Procedure

Step 1

First, we will start from MainForm.cs.

It looks like:



The main part of this portion is a TabControl where we have three tabs: Split, Join and About.

In the Split section, we will do our encoding. Actually, it splits your desired file (that you will select) into a number of encrypted files.

Then, in the Join portion we combine the encrypted files into one file (the same as initially).

Step 2

Let’s start the coding section from the Join portion.

With this, we select our desired file that we want to be encrypted in the near future.



For this, we want an OpenFileDialog, TextBox and a Button.

In the Button, we code:

private void browseButton_Click(object sender, EventArgs e)

        {

            //Browse Button

 

            //No. Of Days : Numeric Up Down

            if (noOfFileUpDown.Value != 0)

                SplitButton.Enabled = true;

 

           // TextBox Disabled

            sourceLocationTextBox.Enabled = true;

 

            if (sourceFileDialog.ShowDialog() == DialogResult.OK)

            {

                sourceLocationTextBox.Text = sourceFileDialog.FileName.ToString();

            }

        }

Explanation

"noOfFileUpDown" is a Numeric Up Down control and it sets the total number of distributions of your selected file.

So, the "Split" button will be enabled when you assign at least 1 (specifically, it should not be equal to 0) to the NumericUpDown control.

Next, we enable the TextBox that stores the path of the selected file.

Finally, if the Dialog Result is Ok then it will assign the selected file’s path to the TextBox else not.

Step 3

The Numeric Up Down control that decides how many divisions of selected file.



In the code:

private void noOfFileUpDown_ValueChanged(object sender, EventArgs e)

        {

            if (sourceLocationTextBox.Enabled==true)

                SplitButton.Enabled = true;

        }

Explanation

It it is enabled when the user selects a File from the Open File Dialog.

Step 4

When the user clicks this button then it Pops-up the Settings Form.



For that, the code will be:

  private void settingButton_Click(object sender, EventArgs e)

        {

            Settings sett = new Settings();

            sett.Show();

        }

Where "Setting" is the name of the form (technically, it is the name of the class).

And, the show() method will pop-up the form.

Step 5

Let’s move to the Settings form.

And, its job is to set the default location for the destination (or, location for the output files).



Here, we have used a TextBox, two Buttons and a Folder Dialog.

Note: I have a default text value as my Desktop path, you can have your own.

So, the code for the yellow Button will be (in other words Browse):

private void folderBrowse_Click(object sender, EventArgs e)

        {

            folderDisplayTextBox.Enabled = true;

 

            if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)

            {

                folderDisplayTextBox.Text = folderBrowserDialog1.SelectedPath;

                BackEnd.outputFolder = folderDisplayTextBox.Text.ToString();

            }

        }

The same as done earlier, assign the selected path of the folder. So, I am skipping the explanation part for this code.

Step 6

Before I move to the Check button (green one) I want to show you the so called Kernel class (BackEnd.cs) where I have defined a few public property variables.

        public static string folderDetination { getset; }

        public static string fileSource { getset; }

        public static int noOfFiles { getset; }

 

        public static string outputFolder { getset; }

        public static String extension { getset; }

I want you to become aware of these property variables that are static in nature. And, I will use these frequently.

Step 7

Back to the "Setting.cs" form, where we have a Big button (check) that finishes the job.

Let’s see what is there.

private void button1_Click(object sender, EventArgs e)

        {

            // Ok Button

 

            BackEnd myBackEnd = new BackEnd();

           // myBackEnd.folderDetination = folderDisplayTextBox.Text.ToString();

            BackEnd.folderDetination = folderDisplayTextBox.Text.ToString();

 

            MessageBox.Show("Your Destination Path is : " + BackEnd.folderDetination);

            //Close The Form

            this.Close();

        }

Here, we have assigned the folderDisplayTextBox (only TextBox) to the BackEnd’s Property that I have shown you in the previous step.

Doing this, we can use this value in the MainForm for processing.

At last, we call the Close() method to close the form.

Step 8

Back to the Main form, we have Split still there.

So, let’s code that which will call a user-defined SplitMethod() in the BackEnd class to do the split.

And, this method requires three arguments.

The first is the folder destination where we will finally put the split file (in other words the output files).

Then the second argument will be the source file that will be split.

And the last argument will be how many divisions there will be of the selected file.

So, let’s see how the code looks like for this.

private void SplitButton_Click(object sender, EventArgs e)

        {

            //Split Button Clicked

            

            BackEnd.fileSource = sourceLocationTextBox.Text.ToString();

            BackEnd.noOfFiles = int.Parse(noOfFileUpDown.Value.ToString());

 

          //MessageBox.Show("Source : " + BackEnd.fileSource + "  -- No. Of Files is : " + BackEnd.noOfFiles + " and   -- Your  Destination :  " + BackEnd.folderDetination);

           bool status = BackEnd.SplitMethod(BackEnd.folderDetination, BackEnd.fileSource, BackEnd.noOfFiles);

 

           if (status == true)

               MessageBox.Show("Your File Has Successfully Coded :)""Success Report"MessageBoxButtons.OK, MessageBoxIcon.Information);

           else

               MessageBox.Show("Got Some ERROR :'( ","Error",MessageBoxButtons.OK,MessageBoxIcon.Error);

 

        }

The SplitMethod() will return a BOOL value depending on the job performance/result.

Step 9

Now, we will look into SplitMethod() that does the split.

public static bool SplitMethod(string destination, string source, int number)

        {

                 // get Extension File Name

                extension = source.Substring(source.Length-3, 3);

 

                // Store The Source File In bytes Array

                Byte[] byteSource = File.ReadAllBytes(source);

 

                //get File Information

                FileInfo fiSource = new FileInfo(source);

 

                // Calculate The Size of Each Part

                int partSize = (int)Math.Ceiling((double)fiSource.Length / number);

 

 

                // The Offset at which we start reading

                int fileoffset = 0;

 

                //Stores each Part

                string currPartPath;

 

                //The FileStream

                FileStream fsPart;

 

                //Stores the Remaing File

                int sizeRemaining = (int)fiSource.Length;

 

                for (int i = 0; i < number; i++)

                {

                    //Stroes The PART

                    currPartPath = destination + "\\" +extension+ fiSource.Name + "." + String.Format(@"{0:D4}", i) + ".slice";

 

                    //Now, we will write it

 

                    if (!File.Exists(currPartPath))

                    {

                        fsPart = new FileStream(currPartPath, FileMode.CreateNew);

                        //Calculate the Remaining Size

                        sizeRemaining = (int)fiSource.Length - (i * partSize);

 

                        if (sizeRemaining < partSize)

                        {

                            partSize = sizeRemaining;

                        }

                        fsPart.Write(byteSource, fileoffset, partSize);

 

 

                        fsPart.Close();

 

                        fileoffset += partSize;

                    }

                }

                return true;

            }

Step 10



Next, we have a Join section where we join those split files into a single file.

First, we need a folder path for where we want to save the output file.

So, we do the same thing as done earlier.

For the Browse button (small Yellow):

private void Browse_Click(object sender, EventArgs e)

        {

            if (folderOutput.ShowDialog() == DialogResult.OK)

            {

                JoinButton.Enabled = true;

                outputFolderTextBox.Enabled = true;

                outputFolderTextBox.Text = folderOutput.SelectedPath;

 

            }

            else

                outputFolderTextBox.Enabled = false;

        }

Step 11

When we click this button, then the joining process will begin. And it calls JoinMethod() from the BackEnd class with two arguments.

First will be the Source Folder destination where the actual split files are.

And the second argument is the new folder path where you want your new file to be.

private void button1_Click(object sender, EventArgs e)

        {

            //Join Button

 

            BackEnd.outputFolder = outputFolderTextBox.Text.ToString();

 

            //MessageBox.Show("Destination: " + BackEnd.folderDetination + "   and Output Folder is : " + BackEnd.outputFolder);

 

            if (outputFolderTextBox.Enabled)

            {

                if (BackEnd.JoinMethod(BackEnd.folderDetination, BackEnd.outputFolder) == true)

                    MessageBox.Show("Succeffully Decode In Your Desired Folder :)""Success Report",MessageBoxButtons.OK,MessageBoxIcon.Information);

                else

                    MessageBox.Show("Sorry !! You Got Some Error :'(""Error Report",MessageBoxButtons.OK,MessageBoxIcon.Error);

            }

        }

Step 12

The JoinMethod method:

public static bool JoinMethod(string folderInput,string folderOutput)

        {

            //get in a Directory

            DirectoryInfo directSource = new DirectoryInfo(folderInput);

            // Get Extension

            FileInfo[] fi = directSource.GetFiles(@"*.slice");

            extension = fi[0].Name.Substring(0, 3);

 

            //FIle Stream to create FILE again

            FileStream fsSource = new FileStream(folderOutput+"/GeneratedFile."+extension,FileMode.Append);

 

            foreach(FileInfo fiPart in directSource.GetFiles(@"*.slice"))

            {

                Byte[] bytePart = System.IO.File.ReadAllBytes(fiPart.FullName);

 

                //Write Those BYTES to create it again

                fsSource.Write(bytePart,0,bytePart.Length);

 

            }

 

            //Close The Stream

            fsSource.Close();

            return true;

        }

Output

I have selected an XML.pdf as input file to be split.



Then, we click on "Split File".



And, it seems like Success. It creates two *.slice files named "pdfXML" something.



These two files are in encrypted form and you can give this to anyone without any fear of data loss.

For decrypting this file, we need to join these sliced files.

For this, go to the "Join" tab and select the folder where these sliced files are.



I have selected Desktop, since my Slice files are there.

And, after clicking this, you are supposed to get this:



So, let’s cross-check this:



And, yes I got my Initial File (XML.pdf).

Note: every time your Generated file’s name will be "GeneratedFile" with their extension.

Conclusion

A basic encryption/decryption tool that can be used on a daily basis. And if you encounter any problem with the code or anything regarding this then it will be my pleasure to answer those. For others, you may go though the enclosed solution of this tool.

Up Next
    Ebook Download
    View all
    Learn
    View all