Skip to content

Instantly share code, notes, and snippets.

@jirkapenzes
Created March 4, 2012 18:09
Show Gist options
  • Save jirkapenzes/1974207 to your computer and use it in GitHub Desktop.
Save jirkapenzes/1974207 to your computer and use it in GitHub Desktop.
Simple class for creating hashes. Default uses MD5 encryption.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Secure.Hash
{
public interface ICryptography
{
string HashString(string original);
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Web;
namespace Secure.Hash
{
public class StringHasher : ICryptography
{
private readonly HashAlgorithm _algorithm;
private readonly Encoding _encoder;
public StringHasher()
: this(MD5.Create()) { }
public StringHasher(HashAlgorithm algorithm)
: this(algorithm, new ASCIIEncoding()) { }
public StringHasher(HashAlgorithm algorithm, Encoding encoder)
{
_algorithm = algorithm;
_encoder = encoder;
}
#region ICryptography Members
public string HashString(string original)
{
string hash;
if (string.IsNullOrEmpty(original))
hash = string.Empty;
else
{
var bytes = _encoder.GetBytes(original);
var result = _algorithm.ComputeHash(bytes);
var sb = new StringBuilder();
for (var i = 0; i < result.Length; i++)
sb.Append(result[i].ToString("X2"));
hash = sb.ToString();
}
return hash;
}
#endregion
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment