MD5 Hash's a string. - CSharp Security

CSharp examples for Security:MD5

Description

MD5 Hash's a string.

Demo Code

/*/*www  . j  av  a2s  .  c  o  m*/
 * @version   : 2.5.0
 * @author    : Ext.NET, Inc. http://www.ext.net/
 * @date      : 2014-10-20
 * @copyright : Copyright (c) 2008-2014, Ext.NET, Inc. (http://www.ext.net/). All rights reserved.
 * @license   : See license.txt and http://www.ext.net/license/. 
 * @website   : http://www.ext.net/
 */
using System.Web.UI;
using System.Web;
using System.Text.RegularExpressions;
using System.Text;
using System.Security.Cryptography;
using System.Globalization;
using System.ComponentModel;
using System.Collections.Generic;
using System.Collections;
using System;

public class Main{
        /// <summary>
        /// MD5Hash's a string. 
        /// </summary>
        public static string ToMD5Hash(this string text)
        {
            if (text.IsEmpty())
            {
                return text;
            }

            MD5 md5 = System.Security.Cryptography.MD5.Create();
            
            byte[] inputBytes = System.Text.Encoding.ASCII.GetBytes(text.Trim());
            byte[] hash = md5.ComputeHash(inputBytes);

            StringBuilder sb = new StringBuilder();

            for (int i = 0; i < hash.Length; i++)
            {
                sb.Append(hash[i].ToString("x2"));
            }

            return sb.ToString();
        }
        /// <summary>
        /// Determine is the string is null or empty.
        /// </summary>
        /// <param name="text"></param>
        /// <returns></returns>
        public static bool IsEmpty(this string text)
        {
            return string.IsNullOrEmpty(text);
        }
}

Related Tutorials