Converts the input string to a byte array and computes the hash. - CSharp System

CSharp examples for System:Byte

Description

Converts the input string to a byte array and computes the hash.

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;/*from w  w w .  j  a va 2 s . com*/

public class Main{
        /// <summary>
        /// Converts the input string to a byte array and computes the hash.
        /// </summary>
        /// <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