SIGN UP MEMBER LOGIN:    
ARTICLE

Encrypt a file using Rijndael

Posted by Muhammad Shakir Articles | Visual C# January 03, 2007
In this artical, we will encrypt a file and embed a encrypted key through wich we encrypt that file
Reader Level:
Download Files:
 

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 weak key is using in 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 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. 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;

}

Login to add your contents and source code to this article
share this article :
post comment
 

hello shakir...why the file is not encrypted even though the window popup appear saying "file encrypt"

Posted by adura aziz Dec 25, 2011

Hello Muhammad Syakir... i wanna ask u ...abou encrypt file using rinjdael.... after the file have been encrypted, where does the file encrypted will store??.. coz...when i'm try running this application.. the state of file i'm trying to encrypt does not encrypted..still in plaintext state...

Posted by adura aziz Dec 25, 2011

Hello Mohamed when i encrypt image file ,I get encrypt without any problem but i need to get encrypt image file thank you

Posted by ahmed bashir Oct 26, 2011

This is very very helpful .... codes are simple but effective. Thank you

Posted by Indranil Paul Aug 08, 2011

RSA is a asymmetric algorithm and can only be used for short messages such as key. For a long message, you will have to use symmetric algorithms. 


I have also using RSA to encrypt the key. If you have still confusion, please let me know, I will guide you how to do.

Thanks 

Posted by Muhammad Shakir Oct 24, 2010
Become a Sponsor
PREMIUM SPONSORS
  • Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
    Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
6 Months Free & No Setup Fees ASP.NET Hosting!
Become a Sponsor