Extension Methods:
using System.Linq;
using System.Security.Cryptography;
using System.Text;
namespace StringExtension
{
public static class StringHashCode
{
public static string GetMD5HashCode(this string str)
{
using (var md5 = MD5.Create())
{
return string.Join("", md5.ComputeHash(Encoding.UTF8.GetBytes(str)).Select(x => x.ToString("x2")));
}
}
public static string GetSha1Code(this string str)
{
using(var sha1 = SHA1.Create())
{
return string.Join("", sha1.ComputeHash(Encoding.UTF8.GetBytes(str)).Select(x => x.ToString("x2")));
}
}
}
}
Test Code:
using Microsoft.VisualStudio.TestTools.UnitTesting;
using StringExtension;
namespace UnitTestStringExtension
{
[TestClass]
public class UnitTestStringMD5Hash
{
[TestMethod]
public void TestGetMD5Hash()
{
var str = "paw123456";
var str_MD5Hash = "dad1e4cf1e972cb49370c217a45875c0";
Assert.AreEqual(str_MD5Hash, str.GetMD5HashCode());
}
[TestMethod]
public void TesGetSha1Code()
{
var str = "paw123456";
var str_Has1 = "e7c5f16f9a848ef11693572b1dd837dfed287d32";
Assert.AreEqual(str_Has1, str.GetSha1Code());
}
}
}