Encrypt and decrypt data using Cryptography namespace

There is a fantastic example in codeproject  to   Encrypt and decrypt data using Cryptography namespace. Unfortunately I could not make the downloaded code worked. That is why I copy the code from the site and build a console application.

1. Create a class for Cryptography.

classSymmCrypto

  {

    ///<remarks>

    /// Supported .Net intrinsic SymmetricAlgorithm classes.

    ///</remarks>

    publicenumSymmProvEnum : int

    {

      DES, RC2, Rijndael

    }

 

    privateSymmetricAlgorithm mobjCryptoService;

 

    ///<remarks>

    /// Constructor for using an intrinsic .Net SymmetricAlgorithm class.

    ///</remarks>

    public SymmCrypto(SymmProvEnum NetSelected)

    {

      switch (NetSelected)

      {

        caseSymmProvEnum.DES:

          mobjCryptoService = newDESCryptoServiceProvider();

          break;

        caseSymmProvEnum.RC2:

          mobjCryptoService = newRC2CryptoServiceProvider();

          break;

        caseSymmProvEnum.Rijndael:

          mobjCryptoService = newRijndaelManaged();

          break;

      }

    }

 

    ///<remarks>

    /// Constructor for using a customized SymmetricAlgorithm class.

    ///</remarks>

    public SymmCrypto(SymmetricAlgorithm ServiceProvider)

    {

      mobjCryptoService = ServiceProvider;

    }

 

    ///<remarks>

    /// Depending on the legal key size limitations of a specific CryptoService provider

    /// and length of the private key provided, padding the secret key with space character

    /// to meet the legal size of the algorithm.

    ///</remarks>

    privatebyte[] GetLegalKey(string Key)

    {

      string sTemp;

      if (mobjCryptoService.LegalKeySizes.Length > 0)

      {

        int lessSize = 0, moreSize = mobjCryptoService.LegalKeySizes[0].MinSize;

        // key sizes are in bits

        while (Key.Length * 8 > moreSize)

        {

          lessSize = moreSize;

          moreSize += mobjCryptoService.LegalKeySizes[0].SkipSize;

        }

        sTemp = Key.PadRight(moreSize / 8, ‘ ‘);

      }

      else

        sTemp = Key;

 

      // convert the secret key to byte array

      returnASCIIEncoding.ASCII.GetBytes(sTemp);

    }

 

    publicstring Encrypting(string Source, string Key)

    {

      byte[] bytIn = System.Text.ASCIIEncoding.ASCII.GetBytes(Source);

      // create a MemoryStream so that the process can be done without I/O files

      System.IO.MemoryStream ms = new System.IO.MemoryStream();

 

      byte[] bytKey = GetLegalKey(Key);

 

      // set the private key

      mobjCryptoService.Key = bytKey;

      mobjCryptoService.IV = bytKey;

 

      // create an Encryptor from the Provider Service instance

      ICryptoTransform encrypto = mobjCryptoService.CreateEncryptor();

 

      // create Crypto Stream that transforms a stream using the encryption

      CryptoStream cs = newCryptoStream(ms, encrypto, CryptoStreamMode.Write);

 

      // write out encrypted content into MemoryStream

      cs.Write(bytIn, 0, bytIn.Length);

      cs.FlushFinalBlock();

 

      // get the output and trim the ” bytes

      byte[] bytOut = ms.GetBuffer();

      int i = 0;

      for (i = 0; i < bytOut.Length; i++)

        if (bytOut[i] == 0)

          break;

 

      // convert into Base64 so that the result can be used in xml

      return System.Convert.ToBase64String(bytOut, 0, i);

    }

 

    publicstring Decrypting(string Source, string Key)

    {

      // convert from Base64 to binary

      byte[] bytIn = System.Convert.FromBase64String(Source);

      // create a MemoryStream with the input

      System.IO.MemoryStream ms = new System.IO.MemoryStream(bytIn, 0, bytIn.Length);

 

      byte[] bytKey = GetLegalKey(Key);

 

      // set the private key

      mobjCryptoService.Key = bytKey;

      mobjCryptoService.IV = bytKey;

 

      // create a Decryptor from the Provider Service instance

      ICryptoTransform encrypto = mobjCryptoService.CreateDecryptor();

 

      // create Crypto Stream that transforms a stream using the decryption

      CryptoStream cs = newCryptoStream(ms, encrypto, CryptoStreamMode.Read);

 

      // read out the result from the Crypto Stream

      System.IO.StreamReader sr = new System.IO.StreamReader(cs);

      return sr.ReadToEnd();

    }

  }

 

2. Type the code in the main program as follow.  

 

 staticvoid Main(string[] args)

 {

 

   SymmCrypto sc = newSymmCrypto(ConAppCryptography.SymmCrypto.SymmProvEnum.DES);

 

   string hello = sc.Encrypting(“Hello world”, “Hello”);

   Console.WriteLine(hello);

   Console.WriteLine(“=============================================================================”);

  hello = sc.Decrypting(hello, “Hello”);

  Console.WriteLine(hello);

  //http://www.codeproject.com/Articles/1967/Encryption-Decryption-with-NET

}

 

You can also download a single solution from http://skydrive.live.com. The sample file name is ConAppCryptography.rar My MSN ID is chanmmn@hotmail.com.

About chanmingman

Since March 2011 Microsoft Live Spaces migrated to Wordpress (http://www.pcworld.com/article/206455/Microsoft_Live_Spaces_Moves_to_WordPress_An_FAQ.html) till now, I have is over 1 million viewers. This blog is about more than 50% telling you how to resolve error messages, especial for Microsoft products. The blog also has a lot of guidance teaching you how to get stated certain Microsoft technologies. The blog also uses as a help to keep my memory. The blog is never meant to give people consulting services or silver bullet solutions. It is a contribution to the community. Thanks for your support over the years. Ming Man is Microsoft MVP since year 2006. He is a software development manager for a multinational company. With 25 years of experience in the IT field, he has developed system using Clipper, COBOL, VB5, VB6, VB.NET, Java and C #. He has been using Visual Studio (.NET) since the Beta back in year 2000. He and the team have developed many projects using .NET platform such as SCM, and HR based applications. He is familiar with the N-Tier design of business application and is also an expert with database experience in MS SQL, Oracle and AS 400.
This entry was posted in .Net and tagged , . Bookmark the permalink.

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.