Remove All Namespace from XML string

//Implemented based on interface, not part of algorithm
        public static string RemoveAllNamespaces(string xmlDocument)
        {
            XElement xmlDocumentWithoutNs = RemoveAllNamespaces(XElement.Parse(xmlDocument));

            return xmlDocumentWithoutNs.ToString();
        }

        //Implemented based on interface, not part of algorithm
        public static string RemoveAllNamespaces(string xmlDocument, XNamespace nameException)
        {
            XElement xmlDocumentWithoutNs = RemoveAllNamespaces(XElement.Parse(xmlDocument));

            return xmlDocumentWithoutNs.ToString();
        }

        //Core recursion function
        private static XElement RemoveAllNamespaces(XElement xmlDocument)
        {
            if (!xmlDocument.HasElements)
            {
                XElement xElement = new XElement(xmlDocument.Name.LocalName);
                xElement.Value = xmlDocument.Value;

                foreach (XAttribute attribute in xmlDocument.Attributes())
                    xElement.Add(attribute);

                return xElement;
            }
            return new XElement(xmlDocument.Name.LocalName, xmlDocument.Elements().Select(el => RemoveAllNamespaces(el)));
        }

Random String Generator C#

using System;
    using System.Security.Cryptography;

    /// <summary>
    /// TODO: Update summary.
    /// </summary>
    public class RandomStringGenerator
    {
        public bool UseSpecialCharacters { get; set; }

        public RandomStringGenerator()
        {
            UseSpecialCharacters = true;
        }

        private static int DEFAULT_MIN_PASSWORD_LENGTH = 8;
        private static int DEFAULT_MAX_PASSWORD_LENGTH = 10;

        // Define supported password characters divided into groups.
        // You can add (or remove) characters to (from) these groups.
        private const string PASSWORD_CHARS_LCASE = “abcdefgijkmnopqrstwxyz”;

        private const string PASSWORD_CHARS_UCASE = “ABCDEFGHJKLMNPQRSTWXYZ”;
        private const string PASSWORD_CHARS_NUMERIC = “23456789”;
        private const string PASSWORD_CHARS_SPECIAL = “*$-+?_&=!%{}/”;

        /// <summary>
        /// Generates a random password.
        /// </summary>
        /// <returns>
        /// Randomly generated password.
        /// </returns>
        /// <remarks>
        /// The length of the generated password will be determined at
        /// random. It will be no shorter than the minimum default and
        /// no longer than maximum default.
        /// </remarks>
        public string Generate()
        {
            return Generate(DEFAULT_MIN_PASSWORD_LENGTH,
                            DEFAULT_MAX_PASSWORD_LENGTH);
        }

        /// <summary>
        /// Generates a random password of the exact length.
        /// </summary>
        /// <param name=”length”>
        /// Exact password length.
        /// </param>
        /// <returns>
        /// Randomly generated password.
        /// </returns>
        public string Generate(int length)
        {
            length = 8;
            return Generate(length, length);
        }

        /// <summary>
        /// Generates a random password.
        /// </summary>
        /// <param name=”minLength”>
        /// Minimum password length.
        /// </param>
        /// <param name=”maxLength”>
        /// Maximum password length.
        /// </param>
        /// <returns>
        /// Randomly generated password.
        /// </returns>
        /// <remarks>
        /// The length of the generated password will be determined at
        /// random and it will fall with the range determined by the
        /// function parameters.
        /// </remarks>
        public string Generate(int minLength,
                                      int maxLength)
        {
            // Make sure that input parameters are valid.
            if (minLength <= 0 || maxLength <= 0 || minLength > maxLength)
                return null;

            // Create a local array containing supported password characters
            // grouped by types. You can remove character groups from this
            // array, but doing so will weaken the password strength.

            char[][] charGroups = new char[][]
            {
                PASSWORD_CHARS_LCASE.ToCharArray(),
                PASSWORD_CHARS_UCASE.ToCharArray(),
                PASSWORD_CHARS_NUMERIC.ToCharArray(),
            };
            if (UseSpecialCharacters)
            {
                charGroups.Append(PASSWORD_CHARS_SPECIAL.ToCharArray());
            }

            // Use this array to track the number of unused characters in each
            // character group.
            int[] charsLeftInGroup = new int[charGroups.Length];

            // Initially, all characters in each group are not used.
            for (int i = 0; i < charsLeftInGroup.Length; i++)

                charsLeftInGroup[i] = charGroups[i].Length;

            // Use this array to track (iterate through) unused character groups.
            int[] leftGroupsOrder = new int[charGroups.Length];

            // Initially, all character groups are not used.
            for (int i = 0; i < leftGroupsOrder.Length; i++)

                leftGroupsOrder[i] = i;

            // Because we cannot use the default randomizer, which is based on the
            // current time (it will produce the same “random” number within a
            // second), we will use a random number generator to seed the
            // randomizer.

            // Use a 4-byte array to fill it with random bytes and convert it then
            // to an integer value.
            byte[] randomBytes = new byte[4];

            // Generate 4 random bytes.
            var rng = new RNGCryptoServiceProvider();

            rng.GetBytes(randomBytes);

            // Convert 4 bytes into a 32-bit integer value.
            int seed = (randomBytes[0] & 0x7f) << 24 |

                       randomBytes[1] << 16 |

                       randomBytes[2] << 8 |

                       randomBytes[3];

            // Now, this is real randomization.
            Random random = new Random(seed);

            // This array will hold password characters.
            char[] password = null;

            // Allocate appropriate memory for the password.
            if (minLength < maxLength)

                password = new char[random.Next(minLength, maxLength + 1)];

            else

                password = new char[minLength];

            // Index of the next character to be added to password.
            int nextCharIdx;

            // Index of the next character group to be processed.
            int nextGroupIdx;

            // Index which will be used to track not processed character groups.
            int nextLeftGroupsOrderIdx;

            // Index of the last non-processed character in a group.
            int lastCharIdx;

            // Index of the last non-processed group.
            int lastLeftGroupsOrderIdx = leftGroupsOrder.Length – 1;

            // Generate password characters one at a time.
            for (int i = 0; i < password.Length; i++)
            {
                // If only one character group remained unprocessed, process it;
                // otherwise, pick a random character group from the unprocessed
                // group list. To allow a special character to appear in the
                // first position, increment the second parameter of the Next
                // function call by one, i.e. lastLeftGroupsOrderIdx + 1.
                if (lastLeftGroupsOrderIdx == 0)
                    nextLeftGroupsOrderIdx = 0;
                else
                    nextLeftGroupsOrderIdx = random.Next(0,
                                                         lastLeftGroupsOrderIdx);

                // Get the actual index of the character group, from which we will
                // pick the next character.
                nextGroupIdx = leftGroupsOrder[nextLeftGroupsOrderIdx];

                // Get the index of the last unprocessed characters in this group.
                lastCharIdx = charsLeftInGroup[nextGroupIdx] – 1;

                // If only one unprocessed character is left, pick it; otherwise,
                // get a random character from the unused character list.
                if (lastCharIdx == 0)
                    nextCharIdx = 0;
                else
                    nextCharIdx = random.Next(0, lastCharIdx + 1);

                // Add this character to the password.
                password[i] = charGroups[nextGroupIdx][nextCharIdx];

                // If we processed the last character in this group, start over.
                if (lastCharIdx == 0)

                    charsLeftInGroup[nextGroupIdx] =

                                              charGroups[nextGroupIdx].Length;

                // There are more unprocessed characters left.
                else
                {
                    // Swap processed character with the last unprocessed character
                    // so that we don’t pick it until we process all characters in
                    // this group.
                    if (lastCharIdx != nextCharIdx)
                    {
                        char temp = charGroups[nextGroupIdx][lastCharIdx];

                        charGroups[nextGroupIdx][lastCharIdx] =

                                    charGroups[nextGroupIdx][nextCharIdx];

                        charGroups[nextGroupIdx][nextCharIdx] = temp;
                    }

                    // Decrement the number of unprocessed characters in
                    // this group.
                    charsLeftInGroup[nextGroupIdx]–;
                }

                // If we processed the last group, start all over.
                if (lastLeftGroupsOrderIdx == 0)
                    lastLeftGroupsOrderIdx = leftGroupsOrder.Length – 1;
                // There are more unprocessed groups left.
                else
                {
                    // Swap processed group with the last unprocessed group
                    // so that we don’t pick it until we process all groups.
                    if (lastLeftGroupsOrderIdx != nextLeftGroupsOrderIdx)
                    {
                        int temp = leftGroupsOrder[lastLeftGroupsOrderIdx];

                        leftGroupsOrder[lastLeftGroupsOrderIdx] =

                                    leftGroupsOrder[nextLeftGroupsOrderIdx];

                        leftGroupsOrder[nextLeftGroupsOrderIdx] = temp;
                    }
                    // Decrement the number of unprocessed groups.
                    lastLeftGroupsOrderIdx–;
                }
            }

            // Convert password characters into a string and return the result.
            return new string(password);
        }
    }

    /// <summary>
    /// Illustrates the use of the RandomPassword class.
    /// </summary>
    ////////public class RandomPasswordTest
    ////////{
    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    ////////[STAThread]
    ////////private static void Main(string[] args)
    ////////{
    ////////    // Print 100 randomly generated passwords (8-to-10 char long).
    ////////    for (int i = 0; i < 100; i++)
    ////////        Console.WriteLine(RandomPassword.Generate(8, 10));
    ////////}
    ////////}

Read to End Stream, (With Error Handling)

/// <summary>
    /// TODO: Update summary.
    /// </summary>
    public class StreamHelper
    {
        public static byte[] ReadToEnd(Stream stream)
        {
            long originalPosition = 0;

            if (stream.CanSeek)
            {
                originalPosition = stream.Position;
                stream.Position = 0;
            }

            try
            {
                byte[] readBuffer = new byte[4096];

                int totalBytesRead = 0;
                int bytesRead;

                while ((bytesRead = stream.Read(readBuffer, totalBytesRead, readBuffer.Length – totalBytesRead)) > 0)
                {
                    totalBytesRead += bytesRead;

                    if (totalBytesRead == readBuffer.Length)
                    {
                        int nextByte = stream.ReadByte();
                        if (nextByte != -1)
                        {
                            byte[] temp = new byte[readBuffer.Length * 2];
                            Buffer.BlockCopy(readBuffer, 0, temp, 0, readBuffer.Length);
                            Buffer.SetByte(temp, totalBytesRead, (byte)nextByte);
                            readBuffer = temp;
                            totalBytesRead++;
                        }
                    }
                }

                byte[] buffer = readBuffer;
                if (readBuffer.Length != totalBytesRead)
                {
                    buffer = new byte[totalBytesRead];
                    Buffer.BlockCopy(readBuffer, 0, buffer, 0, totalBytesRead);
                }
                return buffer;
            }
            finally
            {
                if (stream.CanSeek)
                {
                    stream.Position = originalPosition;
                }
            }
        }
    }

USING ENCRYPTION/DECRYPTION SECURITY SERVICES OF C#.NET 4.0

Using Security Service of c#.NET 4.0

Before starting with encryption and decryption using System.Security, lets first declare the methods of Encryption/Decryption.
This class supports the encryption/decryption on following standards of hashing algorithms: MD5 (Message Digest 5) and different versions of SHA (Using Security Service of c#.NET 4.0

Before starting with encryption and decryption using System.Security, lets first declare the methods of Encryption/Decryption.
This class supports the encryption/decryption on following standards of hashing algorithms: MD5 (Message Digest 5) and different versions of SHA (Secure Hash Algorithm) viz:SHA 1, SHA 256, SHA 338, SHA 512.

This class performs basically two operations ‘ComputeHash’ that encrypts the value sent for the selected hash algorithm.
Another function ‘VerifyHash’ verifies whether the plainText sent has the hashvalue for given algorithm.

This class doesn’t add extra salt bits that are usually added for stronger encryption.

Following is the code for both the operations in the class.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security;
using System.Security.Cryptography;

namespace FMISLayer.Service
{
   public class clsSecurityService
    {
        /// <summary>
        /// Generates a hash for the given plain text value and returns a
        /// base64-encoded result. Before the hash is computed, a random salt
        /// is generated and appended to the plain text. This salt is stored at
        /// the end of the hash value, so it can be used later for hash
        /// verification.
        /// </summary>
        /// <param name=”plainText”>
        /// Plaintext value to be hashed. The function does not check whether
        /// this parameter is null.
        /// </param>
        /// <param name=”hashAlgorithm”>
        /// Name of the hash algorithm. Allowed values are: “MD5”, “SHA1”,
        /// “SHA256”, “SHA384”, and “SHA512” (if any other value is specified
        /// MD5 hashing algorithm will be used). This value is case-insensitive.
        /// </param>        
        /// <returns>
        /// Hash value formatted as a base64-encoded string.
        /// </returns>
       public static string ComputeHash(string plainText,  string hashAlgorithm)
       {        

           // Convert plain text into a byte array.
           byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);       
          

           // Because we support multiple hashing algorithms, we must define
           // hash object as a common (abstract) base class. We will specify the
           // actual hashing algorithm class later during object creation.
           HashAlgorithm hash;

           // Make sure hashing algorithm name is specified.
           if (hashAlgorithm == null)
               hashAlgorithm = “”;

           // Initialize appropriate hashing algorithm class.
           switch (hashAlgorithm.ToUpper())
           {
               case “SHA1”:
                   hash = new SHA1Managed();
                   break;

               case “SHA256”:
                   hash = new SHA256Managed();
                   break;

               case “SHA384”:
                   hash = new SHA384Managed();
                   break;

               case “SHA512”:
                   hash = new SHA512Managed();
                   break;

               default:
                   hash = new MD5CryptoServiceProvider();
                   break;
           }

           // Compute hash value of our plain text with appended salt.
           byte[] hashBytes = hash.ComputeHash(plainTextBytes);                      
           
           // Convert result into a base64-encoded string.
           string hashValue = Convert.ToBase64String(hashBytes);

           // Return the result.
           return hashValue;
       }

       /// <summary>
       /// Compares a hash of the specified plain text value to a given hash
       /// value.
       /// </summary>
       /// <param name=”plainText”>
       /// Plain text to be verified against the specified hash. The function
       /// does not check whether this parameter is null.
       /// </param>
       /// <param name=”hashAlgorithm”>
       /// Name of the hash algorithm. Allowed values are: “MD5”, “SHA1”, 
       /// “SHA256”, “SHA384”, and “SHA512” (if any other value is specified,
       /// MD5 hashing algorithm will be used). This value is case-insensitive.
       /// </param>
       /// <param name=”hashValue”>
       /// Base64-encoded hash value produced by ComputeHash function. This value
       /// includes the original salt appended to it.
       /// </param>
       /// <returns>
       /// If computed hash mathes the specified hash the function the return
       /// value is true; otherwise, the function returns false.
       /// </returns>
       public static bool VerifyHash(string plainText,string hashAlgorithm,string hashValue)
       {
           byte[] hashWithSaltBytes;
           try
           {
               // Convert base64-encoded hash value into a byte array.
               hashWithSaltBytes = Convert.FromBase64String(hashValue);
           }
           catch
           {
               return false;
           }
           // We must know size of hash (without salt).
           int hashSizeInBits, hashSizeInBytes;

           // Make sure that hashing algorithm name is specified.
           if (hashAlgorithm == null)
               hashAlgorithm = “”;

           // Size of hash is based on the specified algorithm.
           switch (hashAlgorithm.ToUpper())
           {
               case “SHA1”:
                   hashSizeInBits = 160;
                   break;

               case “SHA256”:
                   hashSizeInBits = 256;
                   break;

               case “SHA384”:
                   hashSizeInBits = 384;
                   break;

               case “SHA512”:
                   hashSizeInBits = 512;
                   break;

               default: // Must be MD5
                   hashSizeInBits = 128;
                   break;
           }

           // Convert size of hash from bits to bytes.
           hashSizeInBytes = hashSizeInBits / 8;

           // Make sure that the specified hash value is long enough.
           if (hashWithSaltBytes.Length < hashSizeInBytes)
               return false;

           // Allocate array to hold original salt bytes retrieved from hash.
           byte[] saltBytes = new byte[hashWithSaltBytes.Length –
                                       hashSizeInBytes];

           // Copy salt from the end of the hash to the new array.
           for (int i = 0; i < saltBytes.Length; i++)
               saltBytes[i] = hashWithSaltBytes[hashSizeInBytes + i];

           // Compute a new hash string.
           string expectedHashString = ComputeHash(plainText, hashAlgorithm);

           // If the computed hash matches the specified hash,
           // the plain text value must be correct.
           return (hashValue == expectedHashString);
       }

    }
}



But Using this class for the case of MD5, there will be an exception for the case that if the length of the hashvalue is not a multiple of 4.
Hence before using MD5, perform a test that checks if the length of the hashvalue is a multiple of 4, like as below:

if (hashValueToCheckFor.Text.Length % 4 == 0)
            result.Text = clsSecurityService.VerifyHash(plainTextToCheckFor.Text, “MD5”, hashValueToCheckFor.Text).ToString();
        else
            result.Text = “false”;  Hash Algorithm) viz:SHA 1, SHA 256, SHA 338, SHA 512.