Tuesday, January 25, 2011

How to encrypt a datatable and store in xml in c#.net?

Recently I am working with a project where I need to store the XML data in encrypted format. So I decided to encrypt the datatable and then save in xml file in C#.Net. Here are 2 functions that doing the encryption and decryption.

 /// <summary>
        /// This function will encrypt the datatable and write to xml into the filePath provided
        /// </summary>
       /// <param name="dataTable">DataTable to Write XML</param>
       /// <param name="filePath">Output FilePath</param>
        /// <returns>Returns Nothing</returns>
       public static  void EncryptFile(DataTable dataTable,string outPutFilePath)
       {
           XmlTextWriter Xtw = new XmlTextWriter(outPutFilePath, Encoding.UTF8);
           UnicodeEncoding aUE = new UnicodeEncoding();
           byte[] key = aUE.GetBytes("fewlines4biju");

           RijndaelManaged RMCrypto = new RijndaelManaged();
           CryptoStream aCryptoStream = new CryptoStream(Xtw.BaseStream, RMCrypto.CreateEncryptor(key, key), CryptoStreamMode.Write);         
           dataTable.WriteXml(aCryptoStream);
           aCryptoStream.Close();
       }

       /// <summary>
       /// This function will Decrypt the xml file and returns the dataset
       /// </summary>
       /// <param name="filePath">input FilePath</param>
       /// <returns>Returns Dataset</returns>
       public static DataSet  DecryptFile(string inputFilePath)
       {
           DataSet ds = new DataSet();
           FileStream aFileStream = new FileStream(inputFilePath, FileMode.Open);
           StreamReader aStreamReader = new StreamReader(aFileStream);
           UnicodeEncoding aUE = new UnicodeEncoding();
           byte[] key = aUE.GetBytes("fewlines4biju");
           RijndaelManaged RMCrypto = new RijndaelManaged();
           CryptoStream aCryptoStream = new CryptoStream(aFileStream, RMCrypto.CreateDecryptor(key, key), CryptoStreamMode.Read);

           //Restore the data set to memory.
           ds.ReadXml(aCryptoStream);
           aStreamReader.Close();
           aFileStream.Close();
           return ds;
       }

No comments:

Post a Comment