Click here to Skip to main content
15,896,201 members
Articles / Programming Languages / C#

Simple Files Encrypt Decrypt

Rate me:
Please Sign up or sign in to vote.
2.50/5 (7 votes)
10 Sep 2018CPOL2 min read 28.8K   6   5
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.

Image 1

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

Image 2

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

C#
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

C#
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

C#
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:
C#
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.
C#
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.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Web Developer Student
Vietnam Vietnam
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionAlgorithm Used Pin
Member 150345227-Jul-21 8:24
Member 150345227-Jul-21 8:24 
QuestionAlgorithm used Pin
Member 1455431424-Aug-19 21:35
Member 1455431424-Aug-19 21:35 
QuestionIs there an easier way? Pin
George Swan10-Sep-18 11:40
mveGeorge Swan10-Sep-18 11:40 
QuestionInteresting, looks like you are learning some things Pin
raddevus10-Sep-18 10:59
mvaraddevus10-Sep-18 10:59 
SuggestionRadiobuttons Pin
Сергій Ярошко10-Sep-18 9:15
professionalСергій Ярошко10-Sep-18 9:15 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.