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.

RijndaelManaged
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.

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

DES
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.

TripleDES
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)
myAlg.GenerateKey();

// 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
encryptStream.Close();
inFile.Close();
outFile.Close();

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);
Console.WriteLine(Encoding.Unicode.GetString(decryptedBytes));

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.



Thanks,
Paras Sanghani


5 comments: