Click here to Skip to main content
15,867,973 members
Articles / Web Development / ASP.NET
Article

Unleash the power of .NET with encryption

Rate me:
Please Sign up or sign in to vote.
2.97/5 (22 votes)
6 Apr 20069 min read 30.1K   216   14   5
To encrypt and decrypt any personal file such as .doc,.txt,.bmp,.mp3,.wav,.mdb etc

 

Introduction

Unleash the power of .net with encryption<o:p>

Source code: encr.zip<o:p>

 <o:p>

Introduction<o:p>

 <o:p>

Security is the prime issue for personal documents. How can we protect personal files and folders from malicious users? Is there any other method apart from the password protection of folder? Well we can encrypt our documents to provide better protection .Once we encrypt our document it is difficult for other user to read it’s content .Even if they add or append any thing to the document nothing harm will happened to the main content as when we will decrypt the same we will get the content in text format except the newly added part which will be displayed in some non formal text.<o:p>

Ex. All files with .txt extension. This article depicts in detail how to encrypt and decrypt file or folder with “RIJNDAEL” encryption method. You can use this method to encrypt .txt, .bmp, .jpg, .mdb, .wav, MP3 files etc.<o:p>

 <o:p>

Create a new Windows Application project in Visual Studio.NET. The Form will contain five buttons, four textboxes, one imagelist, one treeview and three labels. Add controls to the Form with the following settings:<o:p>

Type<o:p>

Name<o:p>

Type<o:p>

Name<o:p>

Textbox1<o:p>

txtpasswd<o:p>

Button2<o:p>

bttnencrypt<o:p>

Textbox2<o:p>

Textbox1<o:p>

Button3<o:p>

bttndecrypt<o:p>

Textbox3<o:p>

Textbox2<o:p>

Button4<o:p>

bttnrefresh<o:p>

Textbox4<o:p>

txtfilepath<o:p>

Button5<o:p>

bttncls<o:p>

Button1<o:p>

bttnpath<o:p>

Label1<o:p>

lblfilepath<o:p>

 <o:p>

Code:<o:p>

Now it’s time to delve into the code. First add the following import statements<o:p>

Imports System.Security.Cryptography<o:p>

Imports System.Security<o:p>

Imports System.IO<o:p>

Imports System.Text 'TO GET ASCII CONVERSION<o:p>

Imports System.Drawing.Drawing2D 'TO GET ALL BRUSHES<o:p>

Imports System.Drawing.Graphics<o:p>

Imports System.Drawing<o:p>

Imports System.Security.Permissions<o:p>

 <o:p>

First two import statements are required for encryption and decryption process. Last import statement is required for Code Access Security (CAS).<o:p>

Next we will create a subroutine for encryption. This subroutine is called from bttnencrypt.<o:p>

 <o:p>

    Sub encrypt(ByVal encr As SymmetricAlgorithm)<o:p>

        Dim fs, key, ivfile As FileStream<o:p>

        Dim cs As CryptoStream<o:p>

 <o:p>

        Dim fileperm As New FileIOPermission(PermissionState.Unrestricted)<o:p>

        Dim regperm As New RegistryPermission(PermissionState.Unrestricted)<o:p>

        Dim uiperm As New UIPermission(PermissionState.Unrestricted)<o:p>

        Dim newperm As New PermissionSet(PermissionState.None)<o:p>

        newperm.AddPermission(fileperm)<o:p>

        newperm.AddPermission(regperm)<o:p>

        newperm.AddPermission(uiperm)<o:p>

        newperm.PermitOnly()<o:p>

        Try<o:p>

            fs = New FileStream(txtfilepath.Text.ToString, FileMode.Open, FileAccess.ReadWrite)<o:p>

        Catch my As Exception<o:p>

            MsgBox("Following Errors Occured: " & vbCrLf & my.Message & vbCrLf & my.Source)<o:p>

            Exit Sub<o:p>

        End Try<o:p>

 <o:p>

        Dim bytes(CInt(fs.Length) - 1) As Byte<o:p>

        key = New FileStream("C:\key.enc", FileMode.OpenOrCreate)<o:p>

        ivfile = New FileStream("C:\ivfile.enc", FileMode.OpenOrCreate)<o:p>

        Try<o:p>

            encr.Key = keygen()<o:p>

            key.Write(encr.Key, 0, encr.Key.Length)<o:p>

            ivfile.Write(encr.IV, 0, encr.IV.Length)<o:p>

            cs = New CryptoStream(fs, encr.CreateEncryptor(encr.Key, encr.IV), CryptoStreamMode.Write)<o:p>

            Dim i As Integer<o:p>

            Dim ascii As Encoding = Encoding.ASCII<o:p>

 <o:p>

            For i = 0 To fs.Length - 1<o:p>

                bytes(i) = fs.ReadByte<o:p>

 <o:p>

            Next<o:p>

 <o:p>

            TextBox1.Text = "BEFORE ENCRYPTION YOUR FILE CONTAINS :" & vbCrLf & ascii.GetChars(bytes)<o:p>

            fs.SetLength(0)<o:p>

            MsgBox("CHECK FILE", MsgBoxStyle.OKOnly)<o:p>

            cs.Write(bytes, 0, bytes.Length)<o:p>

 <o:p>

        Catch my As Exception<o:p>

            MsgBox(my.Message)<o:p>

 <o:p>

        Finally<o:p>

            If Not key Is Nothing Then<o:p>

                key.Close()<o:p>

            End If<o:p>

            If Not ivfile Is Nothing Then<o:p>

                ivfile.Close()<o:p>

            End If<o:p>

            If Not cs Is Nothing Then<o:p>

                cs.Close()<o:p>

            End If<o:p>

 <o:p>

            If Not fs Is Nothing Then<o:p>

                fs.Close()<o:p>

            End If<o:p>

 <o:p>

 <o:p>

        End Try<o:p>

 <o:p>

This subroutine will create two files key.enc and ivfile.enc at “C:\ “. These two file are essentials for decryption. Please save it in proper place. Otherwise you will be in trouble during decryption. After encryption one message will be displayed like “check file..” so that if you wish you can check the encrypted content of your file. Next I have used a function called keygen () which will take password for encryption and return byte ().<o:p>

 <o:p>

Function keygen() As Byte()<o:p>

        Dim password As String = txtpasswd.Text<o:p>

        Dim add() As Byte = {3, 45, 78, 123, 9, 77}<o:p>

        Dim pwd As New PasswordDeriveBytes(password, add)<o:p>

        Dim pwdbytes() As Byte = pwd.GetBytes(24)<o:p>

        Return pwdbytes<o:p>

    End Function<o:p>

 <o:p>

Declare another subroutine called decrypt which will take two arguments for decryption. This subroutine is called from the click event of bttndecrypt.<o:p>

 <o:p>

Sub decrypt(ByVal encr As SymmetricAlgorithm, ByVal include As Boolean)<o:p>

        Dim fout, key, ivfile As FileStream<o:p>

        Dim cs As CryptoStream<o:p>

        Dim readbyte, newbyte As Integer<o:p>

        fout = New FileStream(txtfilepath.Text.ToString, FileMode.Open, FileAccess.ReadWrite)<o:p>

 <o:p>

        Dim bytes1(CInt(fout.Length) - 1) As Byte<o:p>

 <o:p>

 <o:p>

        key = New FileStream("C:\key.enc", FileMode.Open, FileAccess.ReadWrite)<o:p>

        ivfile = New FileStream("C:\ivfile.enc", FileMode.Open, FileAccess.ReadWrite)<o:p>

        If include Then<o:p>

            Dim key1(key.Length - 1) As Byte<o:p>

            Dim iv(ivfile.Length - 1) As Byte<o:p>

            key.Read(key1, 0, key.Length)<o:p>

            encr.Key = key1<o:p>

            ivfile.Read(iv, 0, iv.Length)<o:p>

            encr.IV = iv<o:p>

        End If<o:p>

        Try<o:p>

            cs = New CryptoStream(fout, encr.CreateDecryptor(encr.Key, encr.IV), CryptoStreamMode.Read)<o:p>

 <o:p>

            Dim ascii As Encoding = Encoding.ASCII<o:p>

            Do<o:p>

                readbyte = cs.Read(bytes1, 0, bytes1.Length)<o:p>

                If readbyte = 0 Then Exit Do<o:p>

            Loop<o:p>

 <o:p>

            TextBox2.Text = "AFTER DECRYPTION YOUR FILE CONTAINS : " & vbCrLf & ascii.GetChars(bytes1)<o:p>

            fout.SetLength(0)<o:p>

 <o:p>

            For newbyte = 0 To bytes1.Length - 1<o:p>

                fout.WriteByte(bytes1(newbyte))<o:p>

            Next<o:p>

        Catch my As Exception<o:p>

            MsgBox(my.Message)<o:p>

        Finally<o:p>

            If Not key Is Nothing Then<o:p>

                key.SetLength(0)<o:p>

                key.Close()<o:p>

            End If<o:p>

            If Not ivfile Is Nothing Then<o:p>

                ivfile.SetLength(0)<o:p>

                ivfile.Close()<o:p>

            End If<o:p>

            If Not fout Is Nothing Then<o:p>

                fout.Close()<o:p>

            End If<o:p>

 <o:p>

 <o:p>

            If Not cs Is Nothing Then<o:p>

                cs.Close()<o:p>

            End If<o:p>

 <o:p>

        End Try<o:p>

 <o:p>

 <o:p>

    End Sub<o:p>

 <o:p>

A few codes I have written for bttnrefresh_click event. This is as follows<o:p>

TextBox1.Text = ""<o:p>

        TextBox2.Text = ""<o:p>

        bttnencrypt.Enabled = True<o:p>

        bttndecrypt.Enabled = True<o:p>

        txtfilepath.Text = ""<o:p>

        txtpasswd.Text = ""<o:p>

 <o:p>

Finally, all of the above subroutines are called as follows<o:p>

 <o:p>

Private Sub bttnencrypt_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles bttnencrypt.Click<o:p>

        If txtfilepath.Text <> "" Then<o:p>

            Dim encr As Rijndael = Rijndael.Create()<o:p>

            encrypt(encr)<o:p>

            bttnencrypt.Enabled = False<o:p>

            bttndecrypt.Enabled = True<o:p>

        Else<o:p>

            MsgBox("Please select path of file or write the physical path of target file")<o:p>

        End If<o:p>

    End Sub<o:p>

Private Sub bttndecrypt_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles bttndecrypt.Click<o:p>

        Dim encr As Rijndael = Rijndael.Create()<o:p>

        decrypt(encr, True)<o:p>

        bttndecrypt.Enabled = False<o:p>

        bttnencrypt.Enabled = True<o:p>

    End Sub<o:p>

 <o:p>

Conclusion<o:p>

This article describes in brief both the encryption and decryption method of rijndael. As I told you earlier if we click bttnencrypt for the first time it will create two files called as key.enc and ivfile.enc. Later decrypt subroutine will use the same file for decryption. Thus the path of these two files is important. Otherwise decryption will not occur. We can avoid such problem in one way by keeping   these two files in a memory location.<o:p>

 To give a professional look to my software “’NCRYPTOR” I have added one treeview and one imagelist to display the directories and subdirectories of all logical drives. Just create a subroutine called treeview() .This subroutine is called from the click event of bttnpath.<o:p>

 <o:p>

Sub treeview()<o:p>

        Dim node, childnode, grandchld, grgrandchld As TreeNode<o:p>

        Dim img As Image<o:p>

        Dim rootdir, subdir, subdr, fname As String<o:p>

        TreeView1.Nodes.Clear()<o:p>

        TreeView1.ImageList = ImageList1<o:p>

        For Each rootdir In Directory.GetLogicalDrives<o:p>

            node = TreeView1.Nodes.Add(rootdir)<o:p>

            If node.Text = "A:\" Then<o:p>

                node.ImageIndex = 4<o:p>

                node.SelectedImageIndex = 4<o:p>

            ElseIf node.Text = "F:\" Then<o:p>

                node.ImageIndex = 1<o:p>

                node.SelectedImageIndex = 1<o:p>

            ElseIf node.Text = "G:\" Then<o:p>

                node.ImageIndex = 1<o:p>

                node.SelectedImageIndex = 1<o:p>

            ElseIf node.Text = "H:\" Then<o:p>

                node.ImageIndex = 1<o:p>

                node.SelectedImageIndex = 1<o:p>

            Else<o:p>

                node.ImageIndex = 3<o:p>

                node.SelectedImageIndex = 3<o:p>

            End If<o:p>

 <o:p>

 <o:p>

            Try<o:p>

                For Each subdir In Directory.GetDirectories(rootdir)<o:p>

                    childnode = node.Nodes.Add(subdir)<o:p>

 <o:p>

                    For Each subdr In Directory.GetDirectories(subdir)<o:p>

 <o:p>

                        grandchld = childnode.Nodes.Add(subdr)<o:p>

                        For Each fname In Directory.GetFiles(subdr)<o:p>

                            grgrandchld = grandchld.Nodes.Add(fname)<o:p>

 <o:p>

                        Next<o:p>

                    Next<o:p>

                Next<o:p>

            Catch my As Exception<o:p>

                MsgBox(my.Message)<o:p>

            End Try<o:p>

 <o:p>

        Next<o:p>

 <o:p>

    End Sub<o:p>

 <o:p>

 <o:p>

Private Sub TreeView1_AfterSelect(ByVal sender As System.Object, ByVal e As System.Windows.Forms.TreeViewEventArgs) Handles TreeView1.AfterSelect<o:p>

 <o:p>

        Label2.Text = e.Node.Text<o:p>

        txtfilepath.Text = Label2.Text<o:p>

    End Sub<o:p>

 <o:p>

 <o:p>

    Private Sub bttnpath_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles bttnpath.Click<o:p>

        treeview()<o:p>

    End Sub<o:p>

 <o:p>

Last but not least I have written a few codes for background color of the form which is as follows<o:p>

 <o:p>

Private Sub transparent_frame(ByVal sender As Object, ByVal e As PaintEventArgs) Handles MyBase.Paint<o:p>

        Dim b As New GraphicsPath()<o:p>

        b.AddRectangle(New Rectangle(0, 0, Me.Width, Me.Height))<o:p>

        Dim br As New PathGradientBrush(b)<o:p>

        br.CenterColor = Color.White<o:p>

        br.CenterPoint = New PointF(120, 30)<o:p>

        Dim colors() As Color = {Color.Blue, Color.AliceBlue, Color.CornflowerBlue, Color.Azure}<o:p>

        br.SurroundColors = colors<o:p>

        Label1.BackColor = Color.Transparent<o:p>

        bttnencrypt.BackColor = Color.Transparent<o:p>

        bttndecrypt.BackColor = Color.Transparent<o:p>

        bttnpath.BackColor = Color.Transparent<o:p>

        bttnrefresh.BackColor = Color.Transparent<o:p>

        Panel1.BackColor = Color.Transparent<o:p>

        Panel2.BackColor = Color.Transparent<o:p>

        Label2.BackColor = Color.Transparent<o:p>

        lblfilepath.BackColor = Color.Transparent<o:p>

        bttncls.BackColor = Color.Transparent<o:p>

        e.Graphics.FillPath(br, b)<o:p>

    End Sub<o:p>

 <o:p>

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Web Developer
India India
I have been working as software developer for last two years.Earlier i worked as faculty for several organisations including TRINITY INTERNATIONAL UNIVERSITY,DELBER,USA.My interests are vb.net,asp.net,sql server and xml.

Comments and Discussions

 
NewsTwo other related encryption articles in CodeProject ... Pin
Tony Selke27-Sep-07 7:01
Tony Selke27-Sep-07 7:01 
GeneralGood artical, but need small changes for new version Pin
Amol Pune4-May-06 2:07
Amol Pune4-May-06 2:07 
GeneralRe: Good artical, but need small changes for new version Pin
KRISHNENDU MUKHERJEE4-May-06 2:39
KRISHNENDU MUKHERJEE4-May-06 2:39 
QuestionSome functions missing Pin
Harshdeep Mehta7-Apr-06 4:22
Harshdeep Mehta7-Apr-06 4:22 
Hi,

Your article is impressive enough, but some function are missing or i am not able to find it outSigh | :sigh: . Those are
1) PasswordDeriveBytes
2) Rijndael.Create() -- what object this is??

Thanks in advance,

Harshdeep Mehta
Mumbai, India
AnswerRe: Some functions missing Pin
KRISHNENDU MUKHERJEE8-Apr-06 21:13
KRISHNENDU MUKHERJEE8-Apr-06 21:13 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.