Serialize an object and compute it's hash code - CSharp System

CSharp examples for System:String Encode Decode

Description

Serialize an object and compute it's hash code

Demo Code

//  Copyright by Contributors
using System.IO;//from   w w w . j a  v a 2s.c  o  m
using System.Runtime.Serialization.Formatters.Binary;
using System.Collections;
using System.Runtime.CompilerServices;
using System.Text;
using System.Collections.Generic;
using System;

public class Main{
        /// <summary>
        /// Serialize an object and compute it's MDWS hash code
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public static string getMD5Hash(object input)
        {
            if (input is string)
            {
                return getMD5Hash((string)input);
            }

            BinaryFormatter bf = new BinaryFormatter();
            MemoryStream ms = new MemoryStream();
            bf.Serialize(ms, input);

            System.Security.Cryptography.MD5 md5 = System.Security.Cryptography.MD5.Create();
            byte[] hashBytes = md5.ComputeHash(ms.GetBuffer());
            StringBuilder sb = new StringBuilder();
            foreach (byte b in hashBytes)
            {
                sb.Append(b.ToString("x2").ToUpper());
            }
            return sb.ToString();
        }
        /// <summary>
        /// Convert a string in to a 32 character MD5 hash code
        /// </summary>
        /// <param name="input">ASCII string</param>
        /// <returns>MD5 hash of string</returns>
        public static string getMD5Hash(string input)
        {
            System.Security.Cryptography.MD5 md5 = System.Security.Cryptography.MD5.Create();
            byte[] hashStringBytes = md5.ComputeHash(System.Text.Encoding.ASCII.GetBytes(input));
            StringBuilder sb = new StringBuilder();
            foreach (byte b in hashStringBytes)
            {
                sb.Append(b.ToString("x2").ToUpper());
            }
            return sb.ToString();
        }
}

Related Tutorials