How to encrypt and decrypt a file by using Visual C#

This article describes how to use the cryptography classes that are provided by the Microsoft .NET Framework to encrypt a text file to an unreadable state, and then to decrypt that text file back to its original format.

Requirements
The following list outlines the recommended hardware, software, network infrastructure, and service packs that you must have:
  • Microsoft Windows 2000 Professional, Windows 2000 Server, Windows 2000 Advanced Server, Windows NT 4.0 Server or Microsoft Windows XP Professional
  • Microsoft Visual Studio 2005 or Microsoft Visual Studio .NET
Encryption and decryption
The System.Security.Cryptographic namespace in the Microsoft .NET Framework provides a variety of tools to help you with encryption and with decryption. The CryptoStream class is one of the many classes that is provided. The CryptoStream class is designed to encrypt or to decrypt content as it is streamed out to a file.

Encrypt a file

To encrypt a file, follow these steps:
  1. Start Visual Studio 2005 or Visual Studio .NET.
  2. Click Visual C# under Projects, and then click Console Application under Templates. Visual C# .NET creates a Static class for you, together with an empty Main() procedure.
  3. Use the using statement (as indicated in the sample code that follows) on the following namespaces:
    • System
    • System.Security
    • System.Security.Cryptography
    • System.Text
    • System.IO

    so that you do not have to qualify declarations from these namespaces later in your code. You must use these statements before any other declarations.
    using System; using System.IO; using System.Security; using System.Security.Cryptography; using System.Runtime.InteropServices; using System.Text;      
  4. Generate a secret key to encrypt and to decrypt the data. The DESCryptoServiceProvider is based on a symmetric encryption algorithm. The symmetric encryption requires a key and an initialization vector (IV) to encrypt the data. To decrypt the data, you must have the same key and the same IV. You must also use the same encryption algorithm. You can generate the keys by using either of the following methods:
    • Method 1 You can prompt the user for a password. Then, use the password as the key and the IV.
    • Method 2 When you create a new instance of the symmetric cryptographic classes, a new key and IV are automatically created for the session. Use the key and IV that are generated by the managed symmetric cryptographic classes to encrypt and to decrypt the file.

      For more information about how to generate and distribute keys, see the Microsoft .NET Framework SDK Documentation, or see the following Microsoft Developer Network (MSDN) Web site:
      Generating keys for encryption and decryption
      http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpguide/html/cpcongeneratingkeysforencryptiondecryption.asp (http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpguide/html/cpcongeneratingkeysforencryptiondecryption.asp)

  5. Add the following function to generate a new key for a session (as noted in Method 2 of step 4):
    //  Call this function to remove the key from memory after use for security. [System.Runtime.InteropServices.DllImport("KERNEL32.DLL", EntryPoint="RtlZeroMemory")] public static extern bool ZeroMemory(ref string Destination, int Length);    // Function to Generate a 64 bits Key. static string GenerateKey()  {  // Create an instance of Symetric Algorithm. Key and IV is generated automatically.  DESCryptoServiceProvider desCrypto =(DESCryptoServiceProvider)DESCryptoServiceProvider.Create();   // Use the Automatically generated key for Encryption.   return ASCIIEncoding.ASCII.GetString(desCrypto.Key); }
  6. Create a method in your class that is named EncryptFile. The EncryptFile class must have the following three parameters:
    • sInputFilename
    • sOutputFilename
    • sKey (The secret key that is used to encrypt and decrypt the file.)
    static void EncryptFile(string sInputFilename,   string sOutputFilename,   string sKey)      
  7. In the EncryptFile procedure, create an input FileStream object and an output FileStream object. These objects can be read from and written to the target files.
    FileStream fsInput = new FileStream(sInputFilename,      FileMode.Open,      FileAccess.Read);  FileStream fsEncrypted = new FileStream(sOutputFilename,      FileMode.Create,      FileAccess.Write);      
  8. Declare an instance of the DESCryptoServiceProvider class. This represents the actual encryption and the actual decryption technology that is used on the files. At this point, you can create a different provider if you prefer to use RSAsecutiry or another cryptographic technique.
    DESCryptoServiceProvider DES = new DESCryptoServiceProvider();      
  9. The cryptographic provider must be provided with your secret key as an array of bytes. The System.Text namespace provides a function that is named GetBytes(). As part of its encoding features, the GetBytes() function takes a string, and then returns an array of bytes. The size of the key is different for each cryptographic technique. For example, Data Encryption Standard (DES) takes a 64-bit key that is equal to 8 bytes or to 8 characters.

See full detail: http://support.microsoft.com/kb/307010

Comments

Popular posts from this blog

Asynchronous Socket Programming in C#

Url Routing MVC TUTORIAL

WCF Chat Sample