Article
    C#
    ADO.Net
    .NET
    ASP.Net & Web Forms
    Custom Controls
    Web Development
    Exception Handling
    XML
    Database
    Security in .Net
    Testing
    Web Services
    Windows Services
    Windows Controls
    WCF
    AJAX
    WPF
    XAML
    Reporting
    Setup
    VB.Net
    LINQ
    JQuery
    SilverLight
    JavaScript
    HTML5
    Crystal Report
    Cloud Computing
    Share Point
    Visual C++
    MVC
    Android
    PHP
    Java
    HTML
    WordPress
    Joomla
    Products
    Drupal
    Windows Phone
    JSON
    LightSwitch
    iPhone/iPad
    Ruby on Rails
    IIS 7
    Windows 8
    CSS/CSS3
    Excel
    MS Access
    Shortcut Keys
    Visual SourceSafe
    Team Foundation Server
    APIs
Follow Us
Follow _MindStick_ on Twitter View MindStick Software's LinkedIn profile View MindStick Software's Facebook profile
Top Contributor
Advertisement
Advertise with Us
Mindstick
Article Article  Forum Forum  Blog Blog  Quiz Quiz  Beginner Beginner  Careers Careers  Contact Contact  Login Login  
Home | Product | Services | About Us | Interview | DeveloperSection | Submit an Article | Submit Blog

Home >> Security in .Net >> Encrypting and Decrypting Files using C sharp
Encrypting and Decrypting Files using C sharp
Encrypting and Decrypting Files using C sharp


by Haider M Rizvi on 7/14/2010 8:12:33 PM

Views: 5989       Comments: 1

Encrypting and Decrypting Files using C#.Net

Here I’m going to show how to encrypt and decrypt text file using C#.Net

Example

//namespace for Input Output file stream

using System.IO;

//name space for Cryptography

using System.Security.Cryptography;

private void btnSelFile_Click(object sender, EventArgs e)

        {

            try

            {

//opening file.

                openFileDialog1.Title = "Open File";

                if (openFileDialog1.ShowDialog() == DialogResult.OK)

                    txtFileName.Text = openFileDialog1.FileName;

            }

            catch (Exception ex)

            {

                MessageBox.Show(ex.Message);

            }

        }

//Encrypting

 

        private void btnEncrypt_Click(object sender, EventArgs e)

        {

            try

            {

                saveKeyDialog2.Title = "Save Key";

                saveFileDialog1.Title = "Save Encrypted file";

// after the user chose where he wants the key file saved

                if (saveKeyDialog2.ShowDialog() == DialogResult.OK)

                {

// after the user chose where he wants the encrypted file saved

                    if (saveFileDialog1.ShowDialog() == DialogResult.OK)

                    {

FileStream fs = File.Create(saveFileDialog1.FileName);

// the cryptographic service provider

we're going to use

TripleDESCryptoServiceProvider tc = new TripleDESCryptoServiceProvider();

// this object links data streams to cryptographic values

CryptoStream cs = new CryptoStream(fs, tc.CreateEncryptor(), CryptoStreamMode.Write);

// This stream reader will read the file to encrypt

                        StreamReader sr = new StreamReader(txtFileName.Text);

// this stream writer will write the new file

                        StreamWriter sw = new StreamWriter(cs);

                        string curline = sr.ReadLine();

                        while (curline != null)

                        {

// Write to the encryption stream

                            sw.Write(curline);

                            curline = sr.ReadLine();

                        }

                        sr.Close();

                        sw.Flush();

                        sw.Close();

//creating key file

FileStream fsKey = File.Create(saveKeyDialog2.FileName);

                        BinaryWriter bw = new BinaryWriter(fsKey);

                        bw.Write(tc.Key);

                        bw.Write(tc.IV);

                        bw.Flush();

                        bw.Close();

                        MessageBox.Show("File Encrypted Successfully");

                        txtFileName.Text = "";

                    }

                }

            }

            catch (Exception ex)

            {

                MessageBox.Show(ex.Message);

            }

        }

 

//Decrypting

 

        private void btnDecrypt_Click(object sender, EventArgs e)

        {

            try

            {

                openFileDialog1.Title = "Open Key File";

                saveFileDialog1.Title = "Save Decrypted File";

                if (openFileDialog1.ShowDialog() == DialogResult.OK)

                {

                    if (saveFileDialog1.ShowDialog() == DialogResult.OK)

                    {

 // The encrypted file

                        FileStream fsFile = File.OpenRead(txtFileName.Text);

 // The key

FileStream fsKey = File.OpenRead(openFileDialog1.FileName);

// The decrypted file

FileStream fsSave = File.Create(saveFileDialog1.FileName);

//Prepare the encryption algorithm and read the key from the key file

TripleDESCryptoServiceProvider csAlgo = new TripleDESCryptoServiceProvider();

                        BinaryReader br = new BinaryReader(fsKey);

                        csAlgo.Key = br.ReadBytes(24);

                        csAlgo.IV = br.ReadBytes(8);

// The cryptographic stream takes in the encrypted file

CryptoStream cs = new CryptoStream(fsFile, csAlgo.CreateDecryptor(), CryptoStreamMode.Read);

// Write the new unecrypted file

                        StreamReader srCleanStream = new StreamReader(cs);

StreamWriter swCleanStream = new StreamWriter(fsSave);

                        swCleanStream.Write(srCleanStream.ReadToEnd());

                        swCleanStream.Close();

                        fsSave.Close();

                        srCleanStream.Close();

                        MessageBox.Show("File Decrypted Successfully");

                    }

                }

            }

            catch (Exception ex)

            {

                MessageBox.Show(ex.Message);

            }           

        }     

 

 

Report Abuse Form
Reason:    
 


Encryption
by John Smith 3/25/2011 4:31:10 AM
Very nice Article.
Report Abuse
Title :
Comment :
Text ColorBackground Color
BoldItalicUnderline
LeftCenterRightJustify
Ordered ListBulleted List
IndentOutdent
Horizontal Rule
SubscriptSuperscript
HyperlinkImage
Design ModeDesign
View HtmlHtml
     
 
Latest Article by Haider M RizviRSS Feed
    
    
    
    
    
    
    
    
    
    
More...
Latest BlogsRSS Feed
    
    
    
    
    
    
    
    
    
    
More...
Top Viewed ArticlesRSS Feed
    
    
    
    
    
    
    
    
    
    
Top Viewed BlogsRSS Feed
    
    
    
    
    
    
    
    
    
    
Latest Interview QuestionsRSS Feed
    
    
    
    
    
    
    
    
    
    
More...
Total Online Users: 2795
Advertisement
MindStick SurveyManager
Advertise with Us
  
Copyright © 2009 - 2013MindStick. All Rights Reserved.