Encrypt a File Using Rijndael

Background

It is very common to be uncertain about which cryptography algorithm is best for encryption and decryption. Because everyone wants to secure his/her data, so that nobody can judge his/her data.

In cryptography algorithms, keys play an important role. If a weak key is used with any algorithm then everyone may decrypt his/her data. For judging any strong cryptography algorithm, always check how strong the key being used is. There are many examples of strong and weak keys of cryptography algorithms like DES, Triple DES, and Rijndael.

  • DES is used one 64-bits key
  • Triple DES is used three 64-bits key
  • Rijndael is used vary (128,160,192,224,256) bits keys

Key

Cryptography keys are divided into two areas. On the behalf of keys, cryptographic algorithms are also divided into two areas.

  1. Symmetric
  2. Asymmetric

Symmetric keys are used for data encryption/decryption. When those algorithms are used these keys are called Symmetric Cryptography Algorithms (the same key is used for both encryption and decryption). These keys are used for large amounts of data. For example DES and Rijndael.

And asymmetric keys are used for symmetric key encryption/decryption for data encryption/decryption. In asymmetric keys, two keys are used; private and public keys. A public key is for encryption and the private key is for decryption. For example RSA and Digital Signatures.

Example

In my example, I am using the Rijndael cryptography symmetric algorithm for data encryption/decryption and RSA cryptography asymmetric algorithm for Rijndael key's encryption/decryption. And the key is read from a PWD file randomly.

Encryption

I am encrypting a file based on a large amount of data. The file data may be any size and any type (for example image or text file). Rijndael uses Cipher Block Chaining (CBC) Mode. A Block Size is 128-bits (standard block size) and the key size is 256-bits that is divided into two parts; key and IV (initial vector).

As you know, it is file based encryption/decryption; I am getting a file name as file input (for example abc.txt) and performing my Rijndael encryption algorithm and getting an encrypted file with an .enc extension. The encrypted file name is shown with the current date and time with the .enc extension (for example 911200191145.enc), that is showing the encrypted file, as file output.

When you encrypt any data then you should secure the key used for data encryption. For this purpose an asymmetric key is used. I am securing my data key using the RSA algorithm. Here the RSA key size is 128-bytes. I am also generating my two pairs of keys; public and private key. Using a public key I am encrypting my data key and another one is public and private key pairs, that is to be sent to another person, so that the other person can decrypt my encrypted key using his public and private key.

You can send a public key publicly. You may use FTP or other resources.

Embed Encrypted Key Into Encrypted Data.

Now I have encrypted the data and the key. But the problem is, how I can provide my encrypted key to the other side for decryption. For securing my data better I am embedding my encrypted key at the end of the encrypted file. Now my Encryption process has completed.

Decryption

On other side, the same process is used but in reverse order. I am getting the .enc encrypted file and extracting all bytes and separating the encrypted data and key. Using the RSA private key, I am decrypting the key. Now I have the actual key. Using that I encrypted my data. I am now getting an encrypted key (for example 911200191145.enc) as file input and performing my Rijndael decryption algorithm and getting the decrypted file with the .dnc extension. The decrypted file name is shown with the current date and time with the .enc extension (for example 119200292512.dnc), that is showing the decrypted file, as file output. I now have my actual data that I had encrypted.

Note:

 

 Cryptography Manager.zip contains definitions of Encryption and Decryption methods

.enc extension for Encrypted File

.dnc extension for Decrypted File

Encryption End

CryptoManager crm = null;

byte[] cryptoKey = null;

byte[] cryptoIV = null;

string[] line = new string[10];

string pwd = null;

 

#region Encryption Button

string encName = null;

string origName;

 

private void btnEnc_Click(object sender, EventArgs e)

{

    try

    {

        DateTime current = DateTime.Now;

        RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();

        byte[] keyToEncrypt;

        byte[] encryptedKey;

        origName = txtBrowse.Text;

        encName = origName + ".dat";

        try

        {

            crm.EncryptData(origName, encName, cryptoKey, cryptoIV);

            FileInfo fi = new FileInfo(origName);

            FileInfo fi2 = new FileInfo(encName);

            //remove readonly attribute

            if ((fi.Attributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly)

            {

                fi.Attributes &= ~FileAttributes.ReadOnly;

            }

            //copy creation and modification time

            fi2.CreationTime = fi.CreationTime;

            fi2.LastWriteTime = fi.LastWriteTime;

            fi2.Attributes = FileAttributes.Normal | FileAttributes.Archive;

            byte[] data = File.ReadAllBytes(encName);

            //delete original file

            File.Delete(encName);

 

            #region write RSA (Public Private) key in xml files

            StreamWriter writer = new StreamWriter("PublicPrivateKey.xml");

            string publicprivatexml = RSA.ToXmlString(true);

            writer.Write(publicprivatexml);

            writer.Close();

            #endregion

 

            keyToEncrypt = System.Text.ASCIIEncoding.Unicode.GetBytes(pwd);

            encryptedKey = RSA.Encrypt(keyToEncrypt, false);

            //using (BinaryWriter bw = new BinaryWriter(File.Create(origName + " " + current.Date.Day.ToString() + current.Date.Month.ToString() + current.Date.Year.ToString() + current.TimeOfDay.Duration().Hours.ToString() + current.TimeOfDay.Duration().Minutes.ToString() + current.TimeOfDay.Duration().Seconds.ToString() + ".enc")))

            using (BinaryWriter bw = new BinaryWriter(File.Create(current.Date.Day.ToString() + current.Date.Month.ToString() + current.Date.Year.ToString() + current.TimeOfDay.Duration().Hours.ToString() + current.TimeOfDay.Duration().Minutes.ToString() + current.TimeOfDay.Duration().Seconds.ToString() + ".enc")))

            {

                //Write data

                bw.Seek(0, SeekOrigin.Begin);

                bw.Write(data);

                bw.Write(encryptedKey);

                bw.Close();

            }

            MessageBox.Show("File Encrypted");

        }

        catch (CryptographicException ex)

        {

            MessageBox.Show(ex.Message);

        }

        catch (IOException ex)

        {

            MessageBox.Show(ex.Message);

        }

        catch (UnauthorizedAccessException ex)

        {

            //i.e. readonly

            MessageBox.Show(ex.Message);

        }

    }

    catch (Exception ex)

    {

        MessageBox.Show(ex.Message);

    }

}

#endregion

}

DECRYPTION END 

#region Decryption Button

 

private void btnDnc_Click(object sender, EventArgs e)

{

    try

    {

        DateTime current = DateTime.Now;

        string encName = txtBrowse.Text + "data" + ".enc";

        RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();

 

        #region Seperate key and data

        byte[] alldata = File.ReadAllBytes(txtBrowse.Text);

        byte[] getencryptedkey = new byte[128];

        byte[] data = new byte[alldata.Length - 128];

        for (int i = 0; i < alldata.Length - 128; i++)

        { data[i] = alldata[i]; }

        for (int i = alldata.Length - 128, j = 0; i < alldata.Length; i++, j++)

        { getencryptedkey[j] = alldata[i]; }

        using (BinaryWriter bw = new BinaryWriter(File.Create(encName)))

        {

            bw.Write(data);

            bw.Close();

        }

        #endregion

 

        #region key decryption

        StreamReader reader = new StreamReader("PublicPrivateKey.xml");

        string publicprivatekeyxml = reader.ReadToEnd();

        RSA.FromXmlString(publicprivatekeyxml);

        reader.Close();

        byte[] decryptedKey = RSA.Decrypt(getencryptedkey, false);

        pwd = System.Text.ASCIIEncoding.Unicode.GetString(decryptedKey);

        byte[] dk = null;

        byte[] div = null;

        crm.getKeysFromPassword(pwd, out dk, out div);

        cryptoKey = dk;

        cryptoIV = div;

        #endregion

 

        string ext = Path.GetExtension(encName).ToLower();

        if (ext != ".enc")

        {

            MessageBox.Show("Please Enter correct File");

            return;

        }

        string dncName = Path.GetDirectoryName(encName) + "\\" + Path.GetFileNameWithoutExtension(encName);

                dncName = current.Date.Day.ToString() + current.Date.Month.ToString() + current.Date.Year.ToString() + current.TimeOfDay.Duration().Hours.ToString() + current.TimeOfDay.Duration().Minutes.ToString() + current.TimeOfDay.Duration().Seconds.ToString() + ".dnc";

        try

        {

            if (crm.DecryptData(encName, dncName, cryptoKey, cryptoIV))

            {

                FileInfo fi = new FileInfo(encName);

                FileInfo fi2 = new FileInfo(dncName);

                if ((fi.Attributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly)

                { fi.Attributes &= ~FileAttributes.ReadOnly; }

                //copy creation and modification time

                fi2.CreationTime = fi.CreationTime;

                fi2.LastWriteTime = fi.LastWriteTime;

                //delete encrypted file

                File.Delete(encName);

                MessageBox.Show("File Decrypted");

            }

            else

            {

                 MessageBox.Show("The file can't be decrypted - probably wrong password");

            }

        }

 

        catch (CryptographicException ex)

        { MessageBox.Show(ex.Message); }

        catch (IOException ex)

        { MessageBox.Show(ex.Message); }

        catch (UnauthorizedAccessException ex)

        { //i.e. readonly

            MessageBox.Show(ex.Message);

        }

    }

    catch (Exception ex)

    { MessageBox.Show(ex.Message); }

}

#endregion 

Random Bases PWD

pwd = "abcdefhz";
//get keys from password
byte[] dk = null;
byte[] div = null;
crm.getKeysFromPassword(pwd,
out dk, out div);
cryptoKey = dk;
cryptoIV = div;
}
catch (FormatException ex)
{
MessageBox.Show(ex.Message);
this.Close();
return;
}

Up Next
    Ebook Download
    View all

    FileInfo in C#

    Read by 9.7k people
    Download Now!
    Learn
    View all