C# Tutorials and offshore development in India
    Tutorials   Resources   Forum   Reviews   Communities   Interview   Jobs   Projects   Training   Your Ad Here    
Silverlight Games | Mentor | Code Converter | Articles | Code Factory | Computer Jokes | Members | Peer Appraisal | IT Companies | Bookmarks | Polls | Revenue Sharing | Lobby | Gift Shop |


Prizes & Awards
My Profile



Active Members
TodayLast 7 Days more...






Resources » Articles » .NET Framework »

Encryption and Decryption using DSACryptoServiceProvider Classes


Posted Date: 26 Apr 2009    Resource Type: Articles    Category: .NET Framework
Author: Ramesh SMember Level: Gold    
Rating: 1 out of 5Points: 10



Introduction

Cryptography is technique of writing information in a secret code and is an ancient art. It is a practice of hiding and securing information from unauthorized users.

In Information Technology, Cryptography is used to protect data from being viewed, to detect whether data has been changed and to transfer information over network in a secured manner. Examples are ATM cards, computer passwords and even within online commercial applications. The Secured Socket Layer (SSL) is a common encryption protocol widely used in e-commerce.

Cryptography in .NET

.NET Framework supports a wide range of encryption methods and practices to implement Cryptography in our applications. The .NET Framework Cryptography Model helps to achieve the following goals:
• Confidentiality: To help protect a user's identity or data from being read.
• Data integrity: To help protect data from being changed.
• Authentication: To ensure that data originates from a particular party.

The following methods can be in .NET to implement cryptographic
Secret-key encryption (symmetric cryptography) - This method performs a transformation on data to keep it from being read by third parties. This type of encryption uses a single shared, secret key to encrypt and decrypt data.
Public-key encryption (asymmetric cryptography) - This technique performs a transformation on data to keep it from being read by third parties. This type of encryption uses a public/private key pair to encrypt and decrypt data.
The following classes in .NET can be used to implement public-key encryption algorithms:

1. DSACryptoServiceProvider
2. RSACryptoServiceProvider
3. ECDiffieHellman (base class)
4. ECDiffieHellmanCng
5. ECDiffieHellmanCngPublicKey (base class)
6. ECDiffieHellmanKeyDerivationFunction (base class)
7. ECDsaCng

I am going to use the DSACryptoServiceProvider class to encrypt some text to memory and then decrypt the text. This class is available in System.Security.Cryptography namespace.

I have written the class ‘MySecurity’ with two public methods Encrypt and Decrypt. Both mothods accept a secret key to encript or decript a string. The reason for pasing a secret key is to uniquely encript or decript the given text to be used by diffent purpose. Any text encripted by using a secret key can only be decrypted by the same secret key.


using System;
using System.IO;
using System.Text;
using System.Security.Cryptography;

public class MySecurity
{
SymmetricAlgorithm objCrptoService = new DESCryptoServiceProvider();
//You can modif the the tempIV
string tempIV = "1b46123aaed34e869af8";


public string Encrypt(string sourceText, string key)
{

// Create a memory stream
MemoryStream objMemStream = new MemoryStream();

//Set the legal keys and initialization verctors
objCrptoService.Key = this.GetLegalsecretKey(key);
objCrptoService.IV = this.GetLegalIV();

// Create a CryptoStream using the memory stream and the cryptographic service provider version
// of the Data Encryption stanadard algorithm key.
CryptoStream objCryptStream = new CryptoStream(objMemStream, objCrptoService.CreateEncryptor(), CryptoStreamMode.Write);

// Create a StreamWriter to write a string to the stream.
StreamWriter objStreamWriter = new StreamWriter(objCryptStream);

// Write the sourceText to the memroy stream.
objStreamWriter.WriteLine(sourceText);

// Close the StreamWriter and CryptoStream objects.
objStreamWriter.Close();
objCryptStream.Close();

// Get an array of bytes that represents the memory stream.
byte[] outputBuffer = objMemStream.ToArray();

// Close the memory stream.
objMemStream.Close();

// Return the encrypted byte array.
return System.Convert.ToBase64String(outputBuffer);
}

public string Decrypt(string encriptedText, string key)
{
//Convert the text into bytest
byte[] ecriptedBytes = System.Convert.FromBase64String(encriptedText);

// Create a memory stream to the passed buffer
MemoryStream objMemStream = new MemoryStream(ecriptedBytes);

//Set the legal keys and initialization verctors
objCrptoService.Key = this.GetLegalsecretKey(key);
objCrptoService.IV = this.GetLegalIV();

// Create a CryptoStream using the memory stream and the cryptographic service provider version
// of the Data Encryption stanadard algorithm key
CryptoStream objCryptStream = new CryptoStream(objMemStream, objCrptoService.CreateDecryptor(), CryptoStreamMode.Read);

// Create a StreamReader for reading the stream.
StreamReader objstreamReader = new StreamReader(objCryptStream);

// Read the stream as a string.
string outputText = objstreamReader.ReadLine();

// Close the streams.
objstreamReader.Close();
objCryptStream.Close();
objMemStream.Close();

return outputText;
}


private byte[] GetLegalsecretKey(string secretKey)
{
string tempKey = secretKey;
objCrptoService.GenerateKey();
byte[] tempBytes = objCrptoService.Key;

int secretKeyLength = tempBytes.Length;

if (tempKey.Length > secretKeyLength)
tempKey = tempKey.Substring(0, secretKeyLength);
else if (tempKey.Length < secretKeyLength)
tempKey = tempKey.PadRight(secretKeyLength, ' ');

return ASCIIEncoding.ASCII.GetBytes(tempKey);
}


private byte[] GetLegalIV()
{
objCrptoService.GenerateIV();
byte[] tempBytes = objCrptoService.IV;
int len = tempBytes.Length;
if (tempIV.Length < len)
tempIV = tempIV.PadRight(len, ' ');
else
tempIV = tempIV.Substring(0, len);

return ASCIIEncoding.ASCII.GetBytes(tempIV);
}


}



The following code uses the MySecurity Class to encript the text “Hello World” using the secret key “123”. The encrypted text is again decrypted using the same secret key.


protected void Button2_Click(object sender, EventArgs e)
{
string source = "Hello World";
Response.Write("Original Text : " + source);

MySecurity objSecurity = new MySecurity();

string encriptedText = objSecurity.Encrypt(source, "123");
Response.Write("Encripted Text : " + encriptedText);


string decriptedText = objSecurity.Decrypt(encriptedText, "123");
Response.Write("Decripted Text : " + decriptedText);
}




Responses


No responses found. Be the first to respond and make money from revenue sharing program.

Feedbacks      
Popular Tags   What are tags ?   Search Tags  
Sign In to add tags.
Using DSACryptoServiceProvider class for encryption and decryption  .  Encryption and Decryption with .NET Framework  .  Encryption and Decryption in ASP.NET  .  Encryption and Decryption in .NET  .  Cryptography in .Net  .  ASP.Net Cryptography  .  

Post Feedback


This is a strictly moderated forum. Only approved messages will appear in the site. Please use 'Spell Check' in Google toolbar before you submit.
You must Sign In to post a response.
Next Resource: Secrets behind converting Strings to Number
Previous Resource: A Small Article on Memory Management
Return to Discussion Resource Index
Post New Resource
Category: .NET Framework


Post resources and earn money!
 
More Resources



dotNet Slackers

About Us    Contact Us    Privacy Policy    Terms Of Use