Created
March 4, 2012 18:09
-
-
Save jirkapenzes/1974207 to your computer and use it in GitHub Desktop.
Simple class for creating hashes. Default uses MD5 encryption.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Text; | |
namespace Secure.Hash | |
{ | |
public interface ICryptography | |
{ | |
string HashString(string original); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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