Search This Blog

Friday, October 21, 2011

Different type of Encryption Technique and Hashing Alogritm in C#.NET

Below mentioned function 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 has verification.

public static string ComputeHash(string Input,string HashAlgorithmName,byte[] saltBytes)
        // If salt is not specified, generate it on the fly.
        if (saltBytes == null)
            // Define min and max salt sizes.
            int minSaltSize = 4;
            int maxSaltSize = 8;

            // Generate a random number for the size of the salt.
            Random random = new Random();
            int saltSize = random.Next(minSaltSize, maxSaltSize);

            // Allocate a byte array, which will hold the salt.
            saltBytes = new byte[saltSize];

            // Initialize a random number generator.
            RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();

            // Fill the salt with cryptographically strong byte values.

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

        // Allocate array, which will hold plain text and salt.
        byte[] plainTextWithSaltBytes =
                new byte[plainTextBytes.Length + saltBytes.Length];

        // Copy plain text bytes into resulting array.
        for (int i = 0; i < plainTextBytes.Length; i++)
            plainTextWithSaltBytes[i] = plainTextBytes[i];

        // Append salt bytes to the resulting array.
        for (int i = 0; i < saltBytes.Length; i++)
            plainTextWithSaltBytes[plainTextBytes.Length + i] = saltBytes[i];

        // 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 (HashAlgorithmName == null)
            HashAlgorithmName = "";

        // Initialize appropriate hashing algorithm class.
        switch (HashAlgorithmName.ToUpper())
            case "SHA1":
                hash = new SHA1Managed();

            case "SHA256":
                hash = new SHA256Managed();

            case "SHA384":
                hash = new SHA384Managed();

            case "SHA512":
                hash = new SHA512Managed();

                hash = new MD5CryptoServiceProvider();

        // Compute hash value of our plain text with appended salt.
        byte[] hashBytes = hash.ComputeHash(plainTextWithSaltBytes);

        // Create array which will hold hash and original salt bytes.
        byte[] hashWithSaltBytes = new byte[hashBytes.Length +

        // Copy hash bytes into resulting array.
        for (int i = 0; i < hashBytes.Length; i++)
            hashWithSaltBytes[i] = hashBytes[i];

        // Append salt bytes to the result.
        for (int i = 0; i < saltBytes.Length; i++)
            hashWithSaltBytes[hashBytes.Length + i] = saltBytes[i];

        // Convert result into a base64-encoded string.
        string hashValue = Convert.ToBase64String(hashWithSaltBytes);

        // Return the result.
        return hashValue;

To use this function you need to import System.Security.Cryptography namespace.

Description of parameter:
1) Parameter name="Input".Input value to be hashed. The function does not check whether this parameter is null.
2) Parameter name="HashAlgorithmName".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.
3) Parameter name="saltBytes". This parameter can be null, in which case a random salt value will be generated.

Note: Hash value formatted as a base64-encoded string.

Now I will describe how to verify this Hash value.Below mentioned function Compares a hash of the specified plain text value to a given hash value. Plain text is hashed with the same salt value as the original hash.

public static bool VerifyHash(string Input,string HashAlgorithmName,string hashValue)
        // Convert base64-encoded hash value into a byte array.
        byte[] hashWithSaltBytes = Convert.FromBase64String(hashValue);

        // We must know size of hash (without salt).
        int hashSizeInBits, hashSizeInBytes;

        // Make sure that hashing algorithm name is specified.
        if (HashAlgorithmName == null)
            HashAlgorithmName = "";

        // Size of hash is based on the specified algorithm.
        switch (HashAlgorithmName.ToUpper())
            case "SHA1":
                hashSizeInBits = 160;

            case "SHA256":
                hashSizeInBits = 256;

            case "SHA384":
                hashSizeInBits = 384;

            case "SHA512":
                hashSizeInBits = 512;

            default: // Must be MD5
                hashSizeInBits = 128;

        // 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 -

        // 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(Input, HashAlgorithmName, saltBytes);

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

Result :

If computed hash mathes the specified hash the function the return value is true; otherwise, the function returns false.

Description of parameter:
1) Parameter name="Input".Input to be verified against the specified hash. The function does not check whether this parameter is null.
2) Parameter name="HashAlgorithmName".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.
3) Parameter name="hashValue". Base64-encoded hash value produced by ComputeHash function. This value includes the original salt appended to it

Monday, October 17, 2011

SQL Server:How to split comma delimited string into rows?

Most of the time we required to split the comma separated string into number of row to insert or some time use it inside the  “in clause”  for DML operation sql query, here is a very good example using the power of XML in SQL query you can do it very easy way. This the best split function in sql 2005/2008 to split a comma separated value or string into temp table  using XML.

Step 1
First of all cast the @commasepvalue  into an XML data type by replacing the “,” comma delimiter with starting and ending tags ''.

declare @commasepvalue varchar(50)='rashmi,ashish,punit,vishal'
SELECT cast('<x>'+replace(@commasepvalue,',','</x><x>')+'</x>' as xml) 
as thexml
 Use 'CROSS APPLY' for splitting the data. The APPLY clause lets you join a table to a table-valued-function. The APPLY clause acts like a JOIN without the ON clause and comes in two flavors: CROSS and OUTER. 
* The OUTER APPLY clause returns all the rows on the left side (@commasepvalue) 

whether they return any rows in the table-valued-function or not. The columns that the
table-valued-function returns are null if no rows are returned.
* The CROSS APPLY only returns rows from the left side (@commasepvalue) 
if the table-valued-function returns rows.
declare @commasepvalue varchar(50)='rashmi,ashish,punit,vishal'
select q2.value from
(SELECT cast('<x>'+replace(@commasepvalue,',','</x><x>')+'</x>' as xml) as thexml)q1 CROSS APPLY
(SELECT x.value('.','varchar(100)') as value FROM thexml.nodes('x') as f(x))q2

Oupput of the Above query is