Stu's Rusty Bucket

Returning Hash strings in .NET

Was trying to compute the hash of a password, but I needed the result as a string.. Looking over the .NET stuff, it only returns the hash as binary (unless I missed some glaringly obvious function)…

anyway here is a simple class that will hash strings passed to it and return them as ascii. You can select ether an MD5 or SHA1 routine.

using System;
using System.Security.Cryptography;

namespace GeneralRoutines
{
    
/// <summary>
    /// Summary description for clsHash.
    /// </summary>
    
public class clsHash
    {
        public enum HashFunctions
        {
            hash_SHA1 
0,
            
hash_MD5
        }

        private System
.Security.Cryptography.HashAlgorithm xHash;

        
public clsHash(HashFunctions htype)
        
{
            
//
            // TODO: Add constructor logic here
            //

            
switch(htype)
            
{
                
case HashFunctions.hash_SHA1:
                    
xHash = new System.Security.Cryptography.SHA1CryptoServiceProvider();
                    break;

                case 
HashFunctions.hash_MD5:
                    
xHash = new System.Security.Cryptography.MD5CryptoServiceProvider();
                    break;
            
}
        }

        
/// <summary>
        /// Computes a hash of the input string and returns it as ascii.
        /// </summary>
        /// <param name="strInput">String</param>
        /// <returns>The ASCIIized string of the hash</returns>
        
public string HashString(string strInput)
        
{
            byte[] xx
;
            
byte[] result

            
xx System.Text.Encoding.UTF8.GetBytes(strInput);

            
xHash.Initialize();
            
result xHash.ComputeHash(xx);

            return 
HashToAscii(result);
        
}


        private string HashToAscii
(byte[] hash)
        
{
            char[] keys 
{'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};

            
string x;
            
int l;

            
"";

            
hash.Length 2;

            for(
int i=0i<li+=1)
            
{
                byte k
;

                
hash[i/2];
                if(
i%== 1)
                    
&amp;= 0xF;
                else
                    
>>= 4;

                
+= keys[k].ToString();

            
}

            
return x;
        
}

    }
}

Posted by on 08/22 at 11:32 PM    
Filed Under : Development
Comments are closed There are no comments on this entry.

<< Back to main