Solved

Encrypt a file using AES encryption in C#

Posted on 2011-03-24
2
2,367 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
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

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

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

Suggested Solutions

SSL stands for “Secure Sockets Layer” and an SSL certificate is a critical component to keeping your website safe, secured, and compliant. Any ecommerce website must have an SSL certificate to ensure the safe handling of sensitive information like…
Worried about if Apple can protect your documents, photos, and everything else that gets stored in iCloud? Read on to find out what Apple really uses to make things secure.
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 …
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 …

756 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