Solved

Encrypt a file using AES encryption in C#

Posted on 2011-03-24
2
2,256 Views
Last Modified: 2012-05-11
There are several resources in the internet which give sample code for encrypting/ decrypting a PLAINTEXT using C#, which uses RijndaelManaged or AES encryption.

I am searching for some sample code which will help me encrypt/ decrypt a file and give me another file as output. The contents of the file to be encrypted can be a PLAINTEXT, BINARY DATA or ZIPPED DATA.

Can someone help please.
0
Comment
Question by:tknayak123
2 Comments
 
LVL 85

Accepted Solution

by:
Mike Tomlinson earned 500 total points
ID: 35209291
Here's an example where the key to encrypt/decrypt is entered by the user into textBox1:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using System.Security.Cryptography;
using System.IO;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        // Make a random string to base your Initialization Vector from:  *This is NOT the password or key!!!
        private const string _IV = "stick some string in here"; // thus must be the same to decrypt your encrypted file!

        private void btnEncrypt_Click(object sender, EventArgs e)
        {
            if (textBox1.Text.Trim().Length > 0)
            {
                using (OpenFileDialog ofd = new OpenFileDialog())
                {
                    ofd.Title = "Select Source File to Encrypt";
                    if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                    {
                        using (SaveFileDialog sfd = new SaveFileDialog())
                        {
                            sfd.Title = "Save Encrypted File To";
                            if (sfd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                            {
                                if (ofd.FileName != sfd.FileName)
                                {
                                    try
                                    {
                                        EncryptFile(ofd.FileName, sfd.FileName, textBox1.Text);
                                        MessageBox.Show("Done Encrypting File!");
                                    }
                                    catch (Exception ex)
                                    {
                                        MessageBox.Show(ex.ToString(), "Error Encrypting File", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                    }
                                }
                                else
                                {
                                    MessageBox.Show("Source and Target File cannot be the same!");
                                }
                            }
                        }
                    }
                }
            }
            else
            {
                MessageBox.Show("Please enter a Key!");
            }
        }

        private void btnDecrypt_Click(object sender, EventArgs e)
        {
            if (textBox1.Text.Trim().Length > 0)
            {
                using (OpenFileDialog ofd = new OpenFileDialog())
                {
                    ofd.Title = "Select Source File to Decrypt";
                    if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                    {
                        using (SaveFileDialog sfd = new SaveFileDialog())
                        {
                            sfd.Title = "Save Decrypted File To";
                            if (sfd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                            {
                                if (ofd.FileName != sfd.FileName)
                                {
                                    try
                                    {
                                        DecryptFile(ofd.FileName, sfd.FileName, textBox1.Text);
                                        MessageBox.Show("Done Decrypting File!");
                                    }
                                    catch (System.Security.Cryptography.CryptographicException cryptoEx)
                                    {
                                        MessageBox.Show(cryptoEx.ToString(), "Invalid Key");
                                    }
                                    catch (Exception ex)
                                    {
                                        MessageBox.Show(ex.ToString(), "Error Reading or Writing File", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                    }
                                }
                                else
                                {
                                    MessageBox.Show("Source and Target File cannot be the same!");
                                }
                            }
                        }
                    }
                }
            }
            else
            {
                MessageBox.Show("Please enter a Key!");
            }
        }

        private void EncryptFile(string sourceFile, string targetFile, string key)
        {
            AesManaged AES = new AesManaged();
            using (MD5CryptoServiceProvider MD5 = new MD5CryptoServiceProvider())
            {
                AES.KeySize = MD5.HashSize; // they are 128 bit compatible
                AES.BlockSize = MD5.HashSize; // they are 128 bit compatible
                AES.IV = MD5.ComputeHash(ASCIIEncoding.ASCII.GetBytes(_IV));
                AES.Key = MD5.ComputeHash(ASCIIEncoding.ASCII.GetBytes(key));
            }
            using (FileStream reader = new FileStream(sourceFile, FileMode.Open, FileAccess.Read))
            {
                using (FileStream writer = new FileStream(targetFile, FileMode.OpenOrCreate, FileAccess.Write))
                {
                    using (CryptoStream cs = new CryptoStream(writer, AES.CreateEncryptor(), CryptoStreamMode.Write))
                    {
                        int bufferSize = 4096;
                        byte[] buffer = new byte[bufferSize];
                        int bytesRead;
                        do
                        {
                            bytesRead = reader.Read(buffer, 0, bufferSize);
                            if (bytesRead != 0)
                            {
                                cs.Write(buffer, 0, bytesRead);
                            }
                        } 
                        while (bytesRead != 0);
                        cs.FlushFinalBlock(); 
                    }
                }
            }
        }

        private void DecryptFile(string sourceFile, string targetFile, string key)
        {
            AesManaged AES = new AesManaged();
            using (MD5CryptoServiceProvider MD5 = new MD5CryptoServiceProvider())
            {
                AES.KeySize = MD5.HashSize; // they are 128 bit compatible
                AES.BlockSize = MD5.HashSize; // they are 128 bit compatible
                AES.IV = MD5.ComputeHash(ASCIIEncoding.ASCII.GetBytes(_IV));
                AES.Key = MD5.ComputeHash(ASCIIEncoding.ASCII.GetBytes(key));
            }
            using (FileStream reader = new FileStream(sourceFile, FileMode.Open, FileAccess.Read))
            {
                using (FileStream writer = new FileStream(targetFile, FileMode.OpenOrCreate, FileAccess.Write))
                {
                    using (CryptoStream cs = new CryptoStream(reader, AES.CreateDecryptor(), CryptoStreamMode.Read))
                    {
                        int bufferSize = 4096;
                        byte[] buffer = new byte[bufferSize];
                        int bytesRead;
                        do
                        {
                            bytesRead = cs.Read(buffer, 0, bufferSize);
                            if (bytesRead != 0)
                            {
                                writer.Write(buffer, 0, bytesRead);
                            }
                        }
                        while (bytesRead != 0);
                    }
                }
            }
        }

    }

}

Open in new window

0
 

Author Closing Comment

by:tknayak123
ID: 35210462
This is the exact code I was looking for.

Thanks
0

Featured Post

Courses: Start Training Online With Pros, Today

Brush up on the basics or master the advanced techniques required to earn essential industry certifications, with Courses. Enroll in a course and start learning today. Training topics range from Android App Dev to the Xen Virtualization Platform.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Provide an easy one stop to quickly get the relevant information on common asked question on Ransomware in Expert Exchange.
Healthcare providers, insurance companies and other covered entities trust eFax Corporate to transmit their most sensitive documents. eFax Corporate can help your organization implement a HIPAA compliant cloud faxing solution.
The Email Laundry PDF encryption service allows companies to send confidential encrypted  emails to anybody. The PDF document can also contain attachments that are embedded in the encrypted PDF. The password is randomly generated by The Email Laundr…
With Secure Portal Encryption, the recipient is sent a link to their email address directing them to the email laundry delivery page. From there, the recipient will be required to enter a user name and password to enter the page. Once the recipient …

786 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question