public class HashAlgorithm
{
/// <summary>
/// 加密类型
/// </summary>
public enum AlgorithmType
{
MD5=1,
SHA1,
SHA256,
SHA384,
SHA512,
}
/// <summary>
/// 返回Hash码的类型
/// </summary>
public enum HashType
{
Base64String = 1,
HexString,
}
/// <summary>
/// 将message进行加密,并返回加密后的Hash码
/// </summary>
/// <param name="message">待加密信息</param>
/// <param name="algorithmType">加密类型,默认为MD5</param>
/// <param name="hashType">加密后得到的Hash的类型,默认返回为十六进制字符串</param>
/// <returns>加密后得到的Hash</returns>
static public String Hash(String message, AlgorithmType algorithmType=AlgorithmType.MD5, HashType hashType=HashType.HexString)
{
if (string.IsNullOrEmpty(message))
{
throw new ArgumentException("Invalid argument");
}
String algorithmName = "";
if (AlgorithmType.MD5 == algorithmType)
algorithmName = HashAlgorithmNames.Md5;//加密类型/算法
else if (AlgorithmType.SHA1 == algorithmType)
algorithmName = HashAlgorithmNames.Sha1;//加密类型/算法
else if (AlgorithmType.SHA256 == algorithmType)
algorithmName = HashAlgorithmNames.Sha256;//加密类型/算法
else if (AlgorithmType.SHA384 == algorithmType)
algorithmName = HashAlgorithmNames.Sha384;//加密类型/算法
else if (AlgorithmType.SHA512 == algorithmType)
algorithmName = HashAlgorithmNames.Sha512;//加密类型/算法
return Hash(message, algorithmName, hashType);
}
static private String Hash(String message, String algorithmName, HashType hashType)
{
// 把待加密信息转换成二进制数据(Convert the message string to binary data.)
IBuffer buffUtf8Msg = CryptographicBuffer.ConvertStringToBinary(message, BinaryStringEncoding.Utf8);
// 创建HashAlgorithmProvider实例(Create a HashAlgorithmProvider object.)
HashAlgorithmProvider algorithmProvider = HashAlgorithmProvider.OpenAlgorithm(algorithmName);
// 获取当前加密类型/名称(retrieve the name of the hashing algorithm.)
//String algorithmTypeUsed = algorithmProvider.AlgorithmName;//得到加密类型/名称
IBuffer buffHash = algorithmProvider.HashData(buffUtf8Msg);//加密// Hash the message.
// Verify that the hash length equals the length specified for the algorithm.
if (buffHash.Length != algorithmProvider.HashLength)//校验加密是否成功
{
throw new Exception("There was an error creating the hash");
}
// 转换成字符串(Convert the hash to a string (for display).)
String strHash="";
if (HashType.Base64String == hashType)
strHash = CryptographicBuffer.EncodeToBase64String(buffHash);
else if (HashType.HexString == hashType)
strHash = CryptographicBuffer.EncodeToHexString(buffHash);
return strHash;// Return the encoded string
}
}
测试:
// Hash a message.
String strMsg = "hello world";//待加密信息
String strEncodedHash = HashAlgorithm.Hash(strMsg);//进行加密,加密类型MD5,返回Hash码为十六进制字符串