Tuesday, August 10, 2010

Encrypting and Decrypting Data in C#.NET.....

Hello Friends,

The security of the Data is most important in Softwares and our job is to protect it from the attackers. You can use cryptography to protect the privacy and integrity of the data that your application stores or transfers. Fortunately, .NET Framework provides classes for several different types of cryptography, including symmetric and asymmetric encryption, hashing, and digital signatures.

Encrypting and Decrypting Data with Symmetric Keys
Many people are introduced to encryption at an early age. Children protect even the most mundane communications from imaginary spies with a secret decoder ring—a toy with two rings that translates encrypted characters to unencrypted characters. The rings on a decoder ring rotate, and a message can be decrypted only when the two rings are lined up correctly. To exchange an encrypted message, the children must first agree on how the rings will line up. After they have exchanged this secret piece of information, they can freely pass encrypted messages without worrying that someone will be able to decrypt them. Even if an imaginary spy had a decoder ring, the spy would need to know how to position the rings to decrypt the message.

Because both the sender and the recipient of the message must know the same secret to encrypt and decrypt a message, secret decoder rings are an example of symmetric key encryption. Symmetric key encryption is a game for children, but it is also the foundation for most encrypted communications today. As children know, encryption is a fun topic. You should enjoy building it into your application, and you'll greatly reduce the chance of private data being compromised.

What Is Symmetric Key Encryption?
Symmetric key encryption, also known as secret-key encryption, is a cryptography technique that uses a single secret key to both encrypt and decrypt data. Symmetric encryption algorithms (also called ciphers) process plain text with the secret encryption key to create encrypted data called cipher text. The cipher text cannot easily be decrypted into the plain text without possession of the secret key.

Symmetric Algorithm Classes in the .NET Framework
Most of the .NET Framework's cryptography functionality is built into the System.Security.Cryptography namespace, including the four implementations of symmetric encryption algorithms. Table 12-2 shows symmetric encryption algorithm classes.

Key Length: 128 through 256 bits, in 32-bit increments
Description: The .NET Framework implementation of the Rijndael symmetric encryption algorithm. As a government encryption standard, this algorithm is also known as Advanced Encryption Standard, or AES.RijndaelManaged is the only .NET Framework symmetric encryption class that is fully managed. All other encryption classes call unmanaged code. Because of this, RijndaelManaged is the preferred choice when your application will be running in a partially trusted environment.

Key Length: Variable
Description: An encryption standard designed to replace DES that uses variable key sizes.

Key Length: 56 bits
Description: The Data Encryption Standard (DES) is a symmetric encryption algorithm that uses relatively short key lengths that are vulnerable to cracking attacks. As a result, it should be avoided. However, it remains commonly used because it is compatible with a wide range of legacy platforms.

Key Length: 156 bits, of which only 112 bits are effectively used for encryption
Description: The .NET Framework implementation of the Triple DES (3DES) symmetric encryption algorithm, it essentially applies the DES algorithm three times.

How to Encrypt and Decrypt Messages Using Symmetric KeysAfter both the encryptor and decryptor have the same key, they can begin exchanging encrypted messages. The .NET Framework makes this process easy. In fact, using encryption is similar to reading and writing to standard files and streams, and it requires only a few additional lines of code. To encrypt or decrypt messages in your application, perform the following tasks:

1. Create a Stream object to interface with the memory or file that you will be reading from or writing to.

2. Create a SymmetricAlgorithm object.

3. Specify the algorithm's key, the IV, or both.

4. Call SymmetricAlgorithm.CreateEncryptor() or SymmetricAlgorithm.CreateDecryptor() to create a ICryptoTransform object.

5. Create a CryptoStream object using the Stream object and the ICryptoTransform object.

6. Read from or write to the CryptoStream object just like any other Stream object.

The following console application demonstrates these steps by reading an unencrypted file (the C:\Boot.ini file), encrypting it with the Rijndael algorithm, and saving the encrypted results as a new file. The application requires the System.IO and System.Security.Cryptography namespaces.
// C#
string inFileName = @"C:\Boot.ini";
string outFileName = @"C:\Boot.ini.enc";

// Step 1: Create the Stream objects
FileStream inFile = new FileStream(inFileName, FileMode.Open, FileAccess.Read);
FileStream outFile = new FileStream(outFileName, FileMode.OpenOrCreate, FileAccess.Write);

// Step 2: Create the SymmetricAlgorithm object
SymmetricAlgorithm myAlg = new RijndaelManaged();

// Step 3: Specify a key (optional)

// Read the unencrypted file into fileData
byte[] fileData = new byte[inFile.Length];
inFile.Read(fileData, 0, (int)inFile.Length);

// Step 4: Create the ICryptoTransform object
ICryptoTransform encryptor = myAlg.CreateEncryptor();

// Step 5: Create the CryptoStream object
CryptoStream encryptStream = new CryptoStream(outFile, encryptor, CryptoStreamMode.Write);

// Step 6: Write the contents to the CryptoStream
encryptStream.Write(fileData, 0, fileData.Length);

// Close the file handles

Because the key is randomly generated, running the application repeatedly generates different results each time. Because the key is not stored, the file can never be decrypted. The key is simply an array of bytes and can be stored by using the BinaryWriter object or by transferring the key across a network.

The code for decrypting a file is almost identical to the code for encrypting a file, except that it must read the encryption key that was used to encrypt the data rather than randomly generate it, and it must call decryption methods instead of encryption methods. To reverse the process to decrypt a file, simply make the following changes to an application:

Change the code for step 3 to read the key and IV that was used to encrypt the data.

Change the code for step 4 to use the CreateDecryptor method instead of CreateEncryptor.

Change the code for step 5 to use the CryptoStreamMode.Read enumeration instead of CryptoStreamMode.Write.

Change the code for step 6 to read from the CryptoStream object.

How to Encrypt and Decrypt Messages Using Asymmetric Encryption
To encrypt and decrypt messages using asymmetric encryption, call the RSACryptoServiceProvider.Encrypt and RSACryptoServiceProvider.Decrypt methods. Both take two parameters:

byte[] rgb An array of bytes containing the message to be encrypted or decrypted.

bool fOAEP A Boolean value. When set to true, encryption and encryption will use OAEP data padding, which is supported only on Windows XP and later operating systems. When set to false, PKCS#1 v1.5 data padding will be used. Both the encryption and decryption methods must use the same data padding.

The most challenging aspect of encryption is converting data into the byte array format. To convert strings to byte arrays, use the System.Text.Encoding.Unicode.GetBytes and System.Text.Encoding.Unicode.GetString methods. For example, the following console application encrypts a string using PKCS#1 v1.5 data padding, and then immediately decrypts and displays the string:

// C#
string messageString = "Hello, World!";
RSACryptoServiceProvider myRsa = new RSACryptoServiceProvider();

byte[] messageBytes = Encoding.Unicode.GetBytes(messageString);
byte[] encryptedMessage = myRsa.Encrypt(messageBytes, false);

byte[] decryptedBytes = myRsa.Decrypt(encryptedMessage, false);

Whichever encoding method you use to convert the data into a byte array, be sure you use a matching decoding method after decrypting the data.

Paras Sanghani

Selecting application types in WPF?

Hello Friends,
As we know WPF - Windows Presentation Foundation is the latest technology introduced by Microsoft in .Net Framework 3.5 and later version.
Let first have a brief look at what is WPF?
Windows Presentation Foundation is the Successor of Windows Forms for desktop application development. Wpf Application differs from traditional Windows Forms Application in several ways. The most notable is that code for the user interface is separated from the code for application functionality. Although the code for project can be done in C#.net , vb.net, etc but the user interface of a WPF project is typically defined using a relatively new declarative syntax called Extensible Application Mark Up Language(XAML).
Wpf development support three kinds of application:

  1. Windows Application
  2. Navigation Application
  3. XAML Browser Application(XBAPs)

Each of the above application has its own benefits and drawbacks and let us check when and where to select which type of application.

1. Windows Application

Windows Application are most similar to Windows Forms applications. Windows applications are Microsoft Windows-driven and provide user experience that is familiar to Windows users and developers alike. Multiple windows can be open at any given time, and there is no built-in sense of navigation or history. We can have the full access of user machine such as Registry, File System. It uses the Windows as their Top-level user interface (UI) element. Window derives from Content Control.

When to use Windows Application?

  • For a user experience that most closely resembles a traditional Windows Form application
  • Menu driven, multiwindow application that combines the rich functionality of a desktop with the rich UI that WPF provides.

2. Navigation Application

This application provides a page-based user experience, similar to the experience of using Web Site. Typically, only a single page can be open at any given time, and the journal functionality keeps records of pages visited and allows back-and-forth navigation. Unlike a Website, however, a navigation application is a compiled application that runs on your desktop computer and, like a Windows application , has full access to the resource of your computer.It uses the Page as their Top-level user interface (UI) element providing similar look and feel as website.

When to user Navigation Application?

  • For user experience that more closely resembles a Web site, you should choose a page-based application. Navigation applications and XBAP applications provide built in navigation functionality that allows you to structure the application paralleling a task, such as in an Internet shopping application or wizard.
  • If application require to access System Resources that fall outside the Internet Security Zone, then XBAP is not a good choice, a better choice would be a Windows application or Navigation application

3. XBAPs Application?

XBAPs application are similar to Navigation Applications, but they are designed to run in Windows Internet Explorer. These applications can be deployed to a server or to a Website and are downloaded when instantiated. Applications of this type do not have full access to a computer's resources. XBAPs run under a partial-trust environment, and resources such as the file system and registry are inaccessible by XBAPS. It uses the Pages as their Top-level user interface (UI) element. XBAP application is not installed on the User machine and thus they have default rights of Internet zones. Howeover, it is technically possible to run XBAP under full trust but it is not recommended because doing so gives full access of your system resources to an application from an untrusted location, thus creating security risks. XBAP are allowed to access isolated storage.

When to use XBAP Application?

  • When you want to deploy the application to a WebServer and have users start if from the hyperlink, thus making it easily accesible to a large-scale audience.
  • If your application does not require access to system resources, XBAP might be good choice.


Paras Sanghani


Paras Sanghani