Home
Manage Your Code
Snippet: Hash Utility (C#)
Title: Hash Utility Language: C#
Description: Class to create Hash Values Views: 190
Author: Richard Wysocki Date Added: 7/8/2008
Copy Code  
1using System;
2using System.IO;
3using System.Security;
4using System.Security.Cryptography;
5using System.Text;
6using System.Collections.Generic;
7
8namespace AjaxClassLibrary
9{
10    public sealed class HashUtility
11    {
12        #region Public Methods   ...        #endregion Public Methods
16
17        public HashUtility()
18        {
19        }
20
21        private static string AddHashSalt(String s)
22        {
23            return ( _salt + s + s.Length.ToString());
24        }
25
26        // Convert String to Byte

27        public static Byte[] ConvertStringToByteArray(String s)
28        {
29            return (new UnicodeEncoding()).GetBytes(HashUtility.AddHashSalt(s));
30        }
31
32        public static Byte[] Hashstring(String s)
33        {
34            Byte[] dataToHash = ConvertStringToByteArray(s);
35            Byte[] hashvalue = ((HashAlgorithm)CryptoConfig.CreateFromName("MD5")).ComputeHash(dataToHash);
36            return hashvalue;
37        }
38
39        public bool Compare(String comparestring, Byte[] HashField)
40        {
41            try
42            {
43                //Convert s1 to byte array

44                Byte[] data1ToHash = ConvertStringToByteArray(comparestring);
45
46                //Create hash value from String using MD5 instance returned by Crypto Config system

47                byte[] hashvalue1 = ((HashAlgorithm)CryptoConfig.CreateFromName("MD5")).ComputeHash(data1ToHash);
48
49                //Memberwise compare of hash value bytes

50                int i = 0;
51                bool same = true;
52                do
53                {
54                    if (hashvalue1[i] != HashField[i])
55                    {
56                        same = false;
57                        break;
58                    }
59                    i++;
60                } while (i < hashvalue1.Length);
61
62                return same;
63            }
64            catch (Exception ex)
65            {
66                throw ex;
67            }
68
69        }
70
71    }
72}
73
74       
75   
76  
77
Usage
            HashUtility Var2 = new HashUtility();
            byte[] hashvalue = HashUtility.Hashstring("Test");
            bool var3 = Var2.Compare("test", hashvalue);