Introduction
Unleash the power of .net with encryption
Source code: encr.zip
Introduction
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.
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.
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:
|
Type |
Name |
Type |
Name |
|
Textbox1 |
txtpasswd |
Button2 |
bttnencrypt |
|
Textbox2 |
Textbox1 |
Button3 |
bttndecrypt |
|
Textbox3 |
Textbox2 |
Button4 |
bttnrefresh |
|
Textbox4 |
txtfilepath |
Button5 |
bttncls |
|
Button1 |
bttnpath |
Label1 |
lblfilepath |
Code:
Now it’s time to delve into the code. First add the following import statements
Imports System.Security.Cryptography
Imports System.Security
Imports System.IO
Imports System.Text 'TO GET ASCII CONVERSION
Imports System.Drawing.Drawing2D 'TO GET ALL BRUSHES
Imports System.Drawing.Graphics
Imports System.Drawing
Imports System.Security.Permissions
First two import statements are required for encryption and decryption process. Last import statement is required for Code Access Security (CAS).
Next we will create a subroutine for encryption. This subroutine is called from bttnencrypt.
Sub encrypt(ByVal encr As SymmetricAlgorithm)
Dim fs, key, ivfile As FileStream
Dim cs As CryptoStream
Dim fileperm As New FileIOPermission(PermissionState.Unrestricted)
Dim regperm As New RegistryPermission(PermissionState.Unrestricted)
Dim uiperm As New UIPermission(PermissionState.Unrestricted)
Dim newperm As New PermissionSet(PermissionState.None)
newperm.AddPermission(fileperm)
newperm.AddPermission(regperm)
newperm.AddPermission(uiperm)
newperm.PermitOnly()
Try
fs = New FileStream(txtfilepath.Text.ToString, FileMode.Open, FileAccess.ReadWrite)
Catch my As Exception
MsgBox("Following Errors Occured: " & vbCrLf & my.Message & vbCrLf & my.Source)
Exit Sub
End Try
Dim bytes(CInt(fs.Length) - 1) As Byte
key = New FileStream("C:\key.enc", FileMode.OpenOrCreate)
ivfile = New FileStream("C:\ivfile.enc", FileMode.OpenOrCreate)
Try
encr.Key = keygen()
key.Write(encr.Key, 0, encr.Key.Length)
ivfile.Write(encr.IV, 0, encr.IV.Length)
cs = New CryptoStream(fs, encr.CreateEncryptor(encr.Key, encr.IV), CryptoStreamMode.Write)
Dim i As Integer
Dim ascii As Encoding = Encoding.ASCII
For i = 0 To fs.Length - 1
bytes(i) = fs.ReadByte
Next
TextBox1.Text = "BEFORE ENCRYPTION YOUR FILE CONTAINS :" & vbCrLf & ascii.GetChars(bytes)
fs.SetLength(0)
MsgBox("CHECK FILE", MsgBoxStyle.OKOnly)
cs.Write(bytes, 0, bytes.Length)
Catch my As Exception
MsgBox(my.Message)
Finally
If Not key Is Nothing Then
key.Close()
End If
If Not ivfile Is Nothing Then
ivfile.Close()
End If
If Not cs Is Nothing Then
cs.Close()
End If
If Not fs Is Nothing Then
fs.Close()
End If
End Try
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 ().
Function keygen() As Byte()
Dim password As String = txtpasswd.Text
Dim add() As Byte = {3, 45, 78, 123, 9, 77}
Dim pwd As New PasswordDeriveBytes(password, add)
Dim pwdbytes() As Byte = pwd.GetBytes(24)
Return pwdbytes
End Function
Declare another subroutine called decrypt which will take two arguments for decryption. This subroutine is called from the click event of bttndecrypt.
Sub decrypt(ByVal encr As SymmetricAlgorithm, ByVal include As Boolean)
Dim fout, key, ivfile As FileStream
Dim cs As CryptoStream
Dim readbyte, newbyte As Integer
fout = New FileStream(txtfilepath.Text.ToString, FileMode.Open, FileAccess.ReadWrite)
Dim bytes1(CInt(fout.Length) - 1) As Byte
key = New FileStream("C:\key.enc", FileMode.Open, FileAccess.ReadWrite)
ivfile = New FileStream("C:\ivfile.enc", FileMode.Open, FileAccess.ReadWrite)
If include Then
Dim key1(key.Length - 1) As Byte
Dim iv(ivfile.Length - 1) As Byte
key.Read(key1, 0, key.Length)
encr.Key = key1
ivfile.Read(iv, 0, iv.Length)
encr.IV = iv
End If
Try
cs = New CryptoStream(fout, encr.CreateDecryptor(encr.Key, encr.IV), CryptoStreamMode.Read)
Dim ascii As Encoding = Encoding.ASCII
Do
readbyte = cs.Read(bytes1, 0, bytes1.Length)
If readbyte = 0 Then Exit Do
Loop
TextBox2.Text = "AFTER DECRYPTION YOUR FILE CONTAINS : " & vbCrLf & ascii.GetChars(bytes1)
fout.SetLength(0)
For newbyte = 0 To bytes1.Length - 1
fout.WriteByte(bytes1(newbyte))
Next
Catch my As Exception
MsgBox(my.Message)
Finally
If Not key Is Nothing Then
key.SetLength(0)
key.Close()
End If
If Not ivfile Is Nothing Then
ivfile.SetLength(0)
ivfile.Close()
End If
If Not fout Is Nothing Then
fout.Close()
End If
If Not cs Is Nothing Then
cs.Close()
End If
End Try
End Sub
A few codes I have written for bttnrefresh_click event. This is as follows
TextBox1.Text = ""
TextBox2.Text = ""
bttnencrypt.Enabled = True
bttndecrypt.Enabled = True
txtfilepath.Text = ""
txtpasswd.Text = ""
Finally, all of the above subroutines are called as follows
Private Sub bttnencrypt_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles bttnencrypt.Click
If txtfilepath.Text <> "" Then
Dim encr As Rijndael = Rijndael.Create()
encrypt(encr)
bttnencrypt.Enabled = False
bttndecrypt.Enabled = True
Else
MsgBox("Please select path of file or write the physical path of target file")
End If
End Sub
Private Sub bttndecrypt_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles bttndecrypt.Click
Dim encr As Rijndael = Rijndael.Create()
decrypt(encr, True)
bttndecrypt.Enabled = False
bttnencrypt.Enabled = True
End Sub
Conclusion
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.
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.
Sub treeview()
Dim node, childnode, grandchld, grgrandchld As TreeNode
Dim img As Image
Dim rootdir, subdir, subdr, fname As String
TreeView1.Nodes.Clear()
TreeView1.ImageList = ImageList1
For Each rootdir In Directory.GetLogicalDrives
node = TreeView1.Nodes.Add(rootdir)
If node.Text = "A:\" Then
node.ImageIndex = 4
node.SelectedImageIndex = 4
ElseIf node.Text = "F:\" Then
node.ImageIndex = 1
node.SelectedImageIndex = 1
ElseIf node.Text = "G:\" Then
node.ImageIndex = 1
node.SelectedImageIndex = 1
ElseIf node.Text = "H:\" Then
node.ImageIndex = 1
node.SelectedImageIndex = 1
Else
node.ImageIndex = 3
node.SelectedImageIndex = 3
End If
Try
For Each subdir In Directory.GetDirectories(rootdir)
childnode = node.Nodes.Add(subdir)
For Each subdr In Directory.GetDirectories(subdir)
grandchld = childnode.Nodes.Add(subdr)
For Each fname In Directory.GetFiles(subdr)
grgrandchld = grandchld.Nodes.Add(fname)
Next
Next
Next
Catch my As Exception
MsgBox(my.Message)
End Try
Next
End Sub
Private Sub TreeView1_AfterSelect(ByVal sender As System.Object, ByVal e As System.Windows.Forms.TreeViewEventArgs) Handles TreeView1.AfterSelect
Label2.Text = e.Node.Text
txtfilepath.Text = Label2.Text
End Sub
Private Sub bttnpath_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles bttnpath.Click
treeview()
End Sub
Last but not least I have written a few codes for background color of the form which is as follows
Private Sub transparent_frame(ByVal sender As Object, ByVal e As PaintEventArgs) Handles MyBase.Paint
Dim b As New GraphicsPath()
b.AddRectangle(New Rectangle(0, 0, Me.Width, Me.Height))
Dim br As New PathGradientBrush(b)
br.CenterColor = Color.White
br.CenterPoint = New PointF(120, 30)
Dim colors() As Color = {Color.Blue, Color.AliceBlue, Color.CornflowerBlue, Color.Azure}
br.SurroundColors = colors
Label1.BackColor = Color.Transparent
bttnencrypt.BackColor = Color.Transparent
bttndecrypt.BackColor = Color.Transparent
bttnpath.BackColor = Color.Transparent
bttnrefresh.BackColor = Color.Transparent
Panel1.BackColor = Color.Transparent
Panel2.BackColor = Color.Transparent
Label2.BackColor = Color.Transparent
lblfilepath.BackColor = Color.Transparent
bttncls.BackColor = Color.Transparent
e.Graphics.FillPath(br, b)
End Sub