Encrypt a File Using Rijndael

Background

It is very common that 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, key plays an important role. If a weak key is used in the algorithm then everyone may decrypt his/her data. For judging any strong crypto algorithm, always checks "how much strong key is using." There are many examples of strong and weak keys of crypto algorithms like DES, Triple DES, and Rijndael.

  • DES uses one 64-bit key
  • Triple DES uses three 64-bit 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. Those algorithms are used these keys are called Symmetric Cryptography Algorithms (Same key is used for both encryption and decryption). These keys are used for large size of data. E.g. DES, Rijndael.

And Asymmetric keys are used for symmetric keys encryption/decryption which is used for data encryption/decryption. In Asymmetric keys, two keys are used; private and public keys. Public key is used for encryption and private key is used for decryption. E.g. RSA, Digital Signatures.

Example

In my example, I am using Rijndael cryptography symmetric algorithm for data encryption/decryption and RSA cryptography asymmetric algorithm for Rijndael key's encryption/decryption. And key input is getting from a PWD file on random bases.

Encryption

I am encrypting file base large data. File data may be any size and any type (e.g. Image or text file). Rijndael is using CBC (Cipher Block Chaining) Mode. Block Size is 128-bits(standard block size) and key size is 256-bits which is dividing 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 (e.g. abc.txt) and performing my Rijndael encryption algorithm and getting encrypted file with .enc extension. Encrypted file name is showing with current date and time with .enc extension (e.g. 911200191145.enc), which is showing encrypted file, as file output.

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

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

Embed Encrypted Key Into Encrypted Data.

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

Decryption

On other side, same process but in reverse order. I am getting .enc encrypted file and extracting all bytes and separating encrypted data and key. Using RSA private key, I am decrypting key. Now I have actual key through which I had encrypted my data. Now, I am getting encrypted key (e.g. 911200191145.enc) as file input and performing my Rijndael decryption algorithm and getting decrypted file with .dnc extension. Decrypted file name is showing with current date and time with .enc extension (e.g. 119200292512.dnc), which is showing decrypted file, as file output. Now, I have my actual data which I had encrypted.

Note:

Crypto 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;
}


Similar Articles