Solved

Encrypt a file using AES encryption in C#

Posted on 2011-03-24
2
2,180 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
Comment Utility
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
Comment Utility
This is the exact code I was looking for.

Thanks
0

Featured Post

How to improve team productivity

Quip adds documents, spreadsheets, and tasklists to your Slack experience
- Elevate ideas to Quip docs
- Share Quip docs in Slack
- Get notified of changes to your docs
- Available on iOS/Android/Desktop/Web
- Online/Offline

Join & Write a Comment

Calculating holidays and working days is a function that is often needed yet it is not one found within the Framework. This article presents one approach to building a working-day calculator for use in .NET.
When the confidentiality and security of your data is a must, trust the highly encrypted cloud fax portfolio used by 12 million businesses worldwide, including nearly half of the Fortune 500.
Access reports are powerful and flexible. Learn how to create a query and then a grouped report using the wizard. Modify the report design after the wizard is done to make it look better. There will be another video to explain how to put the final p…
This video demonstrates how to create an example email signature rule for a department in a company using CodeTwo Exchange Rules. The signature will be inserted beneath users' latest emails in conversations and will be displayed in users' Sent Items…

743 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

Need Help in Real-Time?

Connect with top rated Experts

15 Experts available now in Live!

Get 1:1 Help Now