65.9K
CodeProject is changing. Read more.
Home

Simple Files Encrypt Decrypt

starIconstarIcon
emptyStarIcon
starIcon
emptyStarIconemptyStarIcon

2.50/5 (7 votes)

Sep 10, 2018

CPOL

2 min read

viewsIcon

30529

Everybody has some secret files, and they don't want anyone to see them. So, they need to encrypt them.

Introduction

This post shows you how to encrypt file to protect file content and protect the owner.

You can watch step by step in this video on Youtube: https://www.youtube.com/watch?v=CFfjZfkciQQ.

Background

  • Basic C# instruction
  • File access
  • Windows Form design

Using the Code

1. Open Visual Studio and Create New Windows Form Project

  • Set project type is: Windows Form
  • Project name: by yourself
  • .NET version: 4.0 or higher

2. Design Form like this Figure

Set some properties:

  • TextBox Password: Set password char is *
  • Set value to lables, radio buttons

3. Browse File to Encrypt or Decrypt Code Like This

        private void btBrowse_Click(object sender, EventArgs e)
        {
            OpenFileDialog od = new OpenFileDialog();
            od.Multiselect = false;
            if(od.ShowDialog() == DialogResult.OK)
            {
                tbPath.Text = od.FileName;
            }
        }

if you want to do with multi files, you can change od.Multiselect = true; but you must change some code in the below part.

4. Code for User Select Encrypt or Decrypt

        private void rbEncrypt_CheckedChanged(object sender, EventArgs e)
        {
            if(rbEncrypt.Checked)
            {
                rbDecrypt.Checked = false;
            }
        }

        private void rbDecrypt_CheckedChanged(object sender, EventArgs e)
        {
            if (rbDecrypt.Checked)
                rbEncrypt.Checked = false;
        }

5. Define Global Variables

        byte[] abc;
        byte[,] table;

6. Initial Value for Global Variables in Form Load Event

We have 2 global variables: abc and table.

  • abc is an alphabet, it contains all characters used to encrypt or decrypt. In this use case, abc is an array of bytes with values from 0 to 255.
  • table is a matrix in 2D. Each row of table is all character from abc with row i begin with value in index i of abc:
        private void Form1_Load(object sender, EventArgs e)
        {
            rbEncrypt.Checked = true;

            // init abc and table
            abc = new byte[256];
            for (int i = 0; i < 256; i++)
                abc[i] = Convert.ToByte(i);

            table = new byte[256, 256];
            for(int i = 0; i < 256; i++)
                for(int j = 0; j < 256; j++)
                {
                    table[i, j] = abc[(i + j) % 256];
                }
        }

7. Write the Main Task When the User Clicks to Run Button

  • First, we check input values like:
    • File exist
    • Input password to encrypt or decrypt
  • Then, read all file content to a byte array, convert password to another byte array.
  • Create new array with name is keys, keys is password byte repeat until length of keys equal file content array length.
private void btStart_Click(object sender, EventArgs e)
        {
            // Check input values
            if(!File.Exists(tbPath.Text))
            {
                MessageBox.Show("File does not exist.");
                return;
            }
            if(String.IsNullOrEmpty(tbPassword.Text))
            {
                MessageBox.Show("Password empty. Please enter your password");
                return;
            }

            // Get file content and key for encrypt/decrypt
            try
            {
                byte[] fileContent = File.ReadAllBytes(tbPath.Text);
                byte[] passwordTmp = Encoding.ASCII.GetBytes(tbPassword.Text);
                byte[] keys = new byte[fileContent.Length];
                for (int i = 0; i < fileContent.Length; i++)
                    keys[i] = passwordTmp[i % passwordTmp.Length];

                // Encrypt
                byte[] result = new byte[fileContent.Length];

                if (rbEncrypt.Checked)
                {
                    for(int i = 0; i < fileContent.Length; i++)
                    {
                        byte value = fileContent[i];
                        byte key = keys[i];
                        int valueIndex = -1, keyIndex = -1;
                        for(int j = 0; j < 256; j++)
                            if(abc[j] == value)
                            {
                                valueIndex = j;
                                break;
                            }
                        for(int j = 0; j < 256; j++)
                            if(abc[j] == key)
                            {
                                keyIndex = j;
                                break;
                            }
                        result[i] = table[keyIndex, valueIndex];
                    }
                }
                // Decrypt
                else
                {
                    for (int i = 0; i < fileContent.Length; i++)
                    {
                        byte value = fileContent[i];
                        byte key = keys[i];
                        int valueIndex = -1, keyIndex = -1;                        
                        for (int j = 0; j < 256; j++)
                            if (abc[j] == key)
                            {
                                keyIndex = j;
                                break;
                            }
                        for (int j = 0; j < 256; j++)
                            if (table[keyIndex, j] == value)
                            {
                                valueIndex = j;
                                break;
                            }
                        result[i] = abc[valueIndex];
                    }
                }

                // Save result to new file with the same extension
                String fileExt = Path.GetExtension(tbPath.Text);
                SaveFileDialog sd = new SaveFileDialog();
                sd.Filter = "Files (*" + fileExt + ") | *" + fileExt;
                if(sd.ShowDialog() == DialogResult.OK)
                {
                    File.WriteAllBytes(sd.FileName, result);
                }
            }
            catch
            {
                MessageBox.Show("File is in use. 
                                 Close other program is using this file and try again.");
                return;
            }            
        }

8. Build Project and Enjoy It!

Points of Interest

This is a simple program to encrypt or decrypt file.

If you want to encrypt files, you must change some in part 6 by using for loop in each file that user was selected.