String extension method which converts the input string to hash array. - CSharp System

CSharp examples for System:String Convert

Description

String extension method which converts the input string to hash array.

Demo Code


using System.Text.RegularExpressions;
using System.Text;
using System.Security.Cryptography;
using System.Linq;
using System.Globalization;
using System.Collections.Generic;
using System;//  www . j  a  v  a  2 s.co  m

public class Main{
        /// <summary>
        /// String extension method which converts the input string to hash array.
        /// </summary>
        /// <param name="input">The string on which the method is invoked.</param>
        /// <returns>Returns the hexadecimal string.</returns>
        public static string ToMd5Hash(this string input)
        {
            var md5Hash = MD5.Create();

            // Convert the input string to a byte array and compute the hash.
            var data = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(input));

            // Create a new StringBuilder to collect the bytes
            // and create a string.
            var builder = new StringBuilder();

            // Loop through each byte of the hashed data 
            // and format each one as a hexadecimal string.
            for (int i = 0; i < data.Length; i++)
            {
                builder.Append(data[i].ToString("x2"));
            }

            // Return the hexadecimal string.
            return builder.ToString();
        }
}

Related Tutorials