What you want to see on DotNetFunda.com ?
Go to DotNetFunda.com
Twitter TwitterLinkedIn
YouTubeGoogle
 Online : 13534 |  Welcome, Guest!   Register  Login
Home > Articles > .NET Framework > Implementing Encryption and Decryption In Windows and Web application

Implementing Encryption and Decryption In Windows and Web application

Article posted by Sashys on 5/8/2011 | Views: 5351 | Category: .NET Framework | Level: Beginner | Points: 250 red flag


Security is more important in any type of Application. The encryption and Decryption plays major role.

Introduction

Nowadays,Information Security is becoming too important. Encryption and Decryption is playing major role in Authunticating the Resource. Both Windows and Web application, We must have Security implemented in some way, that brings the whole system more Reliable.

In this article, We would see, how the Encryption and Decryption can be implemented in Both Windows and Webapplication.. This Article will explain the functionality in highlevel with corresponding code snippet, that can be altered based on our software Requirements.


Implementation in Windows Forms

In the Windows application , we can use the encryption and decryption to store important or sensitive data in to Data base by encrypting and the same encrypted value can be decrypted and used in the application. Banking domain uses encryption and decryption with more important. That brings the whole system more reliable as i mentioned earlier. Please follow the code and corresponding Explanation to understand the same.


using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Text;

using System.Windows.Forms;

using System.Security.Cryptography;

using System.IO;

namespace EncryptionDecryption

{

    public partial class Security : Form

    {

        public Security()

        {

            InitializeComponent();

        }

        public string strUsrname = "";

        public string strPwd = "";

        public string strEncryptValue = "";

        private void BtnSubmit_Click(object sender, EventArgs e)

        {

              strUsrname = TxtUsername.Text.Trim();

              strPwd = TxtPassword.Text.Trim();

              strEncryptValue=Encrypt(strUsrname, strPwd);

              label4.Text = strEncryptValue.Trim();

          

        }

 

        public static string Encrypt(string strTextValue, string Password)

        {

            //Convert Stringvalue to Array

            byte[] TextArray = System.Text.Encoding.Unicode.GetBytes(strTextValue);

 

            //We will change tha password to Key and IV (Initialization Vector) and using All the Possible Values, we prepare the password

            PasswordDeriveBytes objPwdDeriBytes = new PasswordDeriveBytes(Password, new byte[] {0x76, 0x65,  0x6e,0x65 , 0x4d,

                                                                                         0x20, 0x64, 0x76,0x61 , 0x64, 0x65,0x49 });

 

         //The Encryption model Rijndael uses key length as 32bytes and IV uses 16 bytes by default.

            byte[] ByteencryptedValue = Encrypt(TextArray,

                     objPwdDeriBytes.GetBytes(32), objPwdDeriBytes.GetBytes(16));

            //Finally we convert array to string - 64 byte conversion is recommeded here as all the byte values may not be converted to Characters.

            return Convert.ToBase64String(ByteencryptedValue);

 

        }

 

        public static byte[] Encrypt(byte[] strTextValue, byte[] ByteKey, byte[] ByteIV)

        {

            

            MemoryStream objMemoryStream = new MemoryStream();

 

            Rijndael objAlgorithRIJ = Rijndael.Create();

 

            // Now set the key and the IV.

            objAlgorithRIJ.Key = ByteKey;

            objAlgorithRIJ.IV = ByteIV;

 

            // CryptoStream will help to write data in to stream and out put can be stored in the memory stream.

            CryptoStream objCryptoStream = new CryptoStream(objMemoryStream,

               objAlgorithRIJ.CreateEncryptor(), CryptoStreamMode.Write);

 

            // Data becomes encrypted

            objCryptoStream.Write(strTextValue, 0, strTextValue.Length);

 

            objCryptoStream.Close();

 

            //Get the Encrypt data from Memory Stream.

            byte[] ByteencryptedValue = objMemoryStream.ToArray();

 

            return ByteencryptedValue;

        }

 

        public static string Decrypt(string strTextValue, string Password)

        {

 

            byte[] ByteObj = Convert.FromBase64String(strTextValue);

 

            PasswordDeriveBytes ByteencryptedValue = new PasswordDeriveBytes(Password,

                new byte[] {0x76, 0x65,  0x6e,0x65 , 0x4d,

            0x20, 0x64, 0x76,0x61 , 0x64, 0x65,0x49 });

 

            byte[] bytedecryptedValue = Decrypt(ByteObj,

                ByteencryptedValue.GetBytes(32), ByteencryptedValue.GetBytes(16));

 

            return System.Text.Encoding.Unicode.GetString(bytedecryptedValue);

        }

 

 

        public static byte[] Decrypt(byte[] strTextValue,

                                byte[] ByteKey, byte[] ByteIV)

        {

 

            MemoryStream objMemoryStream = new MemoryStream();

            Rijndael objAlgorithRIJ = Rijndael.Create();

 

            objAlgorithRIJ.Key = ByteKey;

            objAlgorithRIJ.IV = ByteIV;

          

            CryptoStream objCryptoStream = new CryptoStream(objMemoryStream,

                objAlgorithRIJ.CreateDecryptor(), CryptoStreamMode.Write);

            objCryptoStream.Write(strTextValue, 0, strTextValue.Length);

            objCryptoStream.Close();

          

            byte[] Bytedecryptedvalue = objMemoryStream.ToArray();

            return Bytedecryptedvalue;

        }

 

        private void BtnDecrypt_Click(object sender, EventArgs e)

        {

            //Pull Encrypted Value from the Database  for the input[Username / Password] , and  tha can be used based on our Requirements.

            //Here we show on the screen.

            string strDecryptValue = Decrypt(strEncryptValue , strPwd);

           

            label5.Text = strDecryptValue.Trim();

 

               

        }

    }

}


Implementing in Web Forms

WebApplication are distributed on the internet, and that requires more security as the end users are very huge. In order to transfer data online, we need to implement Encryption and Decryption. But In this article, we would see how Different parts/sections of webconfig can be encrypted.

Imports System.Web.Configuration

 

 

Partial Class _Default

    Inherits System.Web.UI.Page

    Private strprovider As String = "RSAProtectedConfigurationProvider"

    'Private strprovider As String = "ProviderArea"

    Private strConfigsection As String = "connectionStrings"

 

Protected Sub Encrypt_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles     

                                                                              Encrypt.Click

        Dim objConfiguration As Configuration = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath)

        Dim objConfigurationSection As ConfigurationSection = objConfiguration.GetSection(strConfigsection)

        If Not objConfigurationSection Is Nothing Then

            objConfigurationSection.SectionInformation.ProtectSection(strprovider)

            objConfiguration.Save()

        End If

    End Sub

 

    Protected Sub Decrypt_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles

                                                                                Decrypt.Click

        Dim objConfiguration As Configuration = WebConfigurationManager.OpenWebConfiguration

                                                                   (Request.ApplicationPath)

        Dim objConfigurationSection As ConfigurationSection = objConfiguration.GetSection

                                                                          (strConfigsection)

        If Not objConfigurationSection Is Nothing 

                             And  objConfigurationSection.SectionInformation.IsProtected Then

            objConfigurationSection.SectionInformation.UnprotectSection()

            objConfiguration.Save()

        End If

    End Sub

End Class

Note: The provider name can be found in the Machine.config file, which is located at \Windows\Microsoft.Net\Framework\v2.x\Config

Step1: Create the website appliction and add two buttons on it. Write the above code in each button event.

Step2: Run the App [Add the Web.config file if you don't have one - Will ask you to add when you run at first time].

Step3: Click the Encrypt Button and come back to Code - You will get a popup saying the webconfig file has changed as shown below. Say yes to reload and open the config file, where you can find the Connectstring got encrypted .

Now you can see the Decrypted values in the connection string

Step4:Come back to Browser and click the Decrypt Button to get decrypted. As mentioned in the Step3, it will again ask you to read load the webconfig. Say yes and see the connection string now , it got Decrypted as shown below:


Conclusion

The code would just help to get an idea that how to encrypt and decrypt the values in both windows and web application. Based on Requirements , we can make use of it accordingly.

If you like this article, subscribe to our RSS Feed. You can also subscribe via email to our Interview Questions, Codes and Forums section.

Page copy protected against web site content infringement by Copyscape
Found interesting? Add this to:



Please Sign In to vote for this post.

Experience:6 year(s)
Home page:http://www.dotnetfunda.com
Member since:Tuesday, April 19, 2011
Level:Starter
Status: [Member]
Biography:Programming is kind of Art. Let us learn it!!
 Responses
Posted by: Akiii | Posted on: 09 May 2011 01:40:22 AM | Points: 25

hi sasi.......

good topic to select in the present scenario.....
Could you please explain ....what is this....

{0x76, 0x65, 0x6e,0x65 , 0x4d,0x20, 0x64, 0x76,0x61 , 0x64, 0x65,0x49 });

As this coding a little bit high level for me.....still i will try to study and understand it.....

Thanks and Regards
Akiii

Posted by: Susanthampy | Posted on: 09 May 2011 04:38:30 AM | Points: 25

Good.................................


Refer Microsoft Enterprise Library 5.0 (Cryptography application block)

http://msdn.microsoft.com/en-us/library/ff664484(v=PandP.50).aspx



Posted by: Susanthampy | Posted on: 18 May 2011 04:31:28 AM | Points: 25

Gud..............

>> Write Response - Respond to this post and get points
Related Posts

This article delves into the feature (of SQL server) of returning the multiple resultsets through stored procedure and handling such resultsets in C# for LINQTOSQL.

This article has 12 important FAQ's and will cover Unit testing, load testing, automated testing, database testing and code coverage.

This is continutaion of earlier article on the same subject, delving into long weak references.

Here I am showing how you can invoke a method asynchronously using delegates and AsyncCallback

The purpose of this article is to describe some of the practical uses of the Reflection.

More ...
About Us | Contact Us | The Team | Advertise | Software Development | Write for us | Testimonials | Privacy Policy | Terms of Use | Link Exchange | Members | Go Top
General Notice: If you find plagiarised (copied) contents on this page, please let us know the original source along with your correct email id (to communicate) for further action.
Copyright © DotNetFunda.Com. All Rights Reserved. Copying or mimicking the site design and layout is prohibited. Logos, company names used here if any are only for reference purposes and they may be respective owner's right or trademarks. | 5/25/2013 6:58:00 AM