Skip to content

Instantly share code, notes, and snippets.

@wangye
Created March 7, 2012 02:38
Show Gist options
  • Save wangye/1990537 to your computer and use it in GitHub Desktop.
Save wangye/1990537 to your computer and use it in GitHub Desktop.
C# Reflection MD5/SHA1 Hash
//
// Description: C# Reflection MD5/SHA1 Hash
// Author: wangye <pcn88 at hotmail dot com>
// Website: http://wangye.org
// For more information please visit:
// http://wangye.org/blog/archives/134/
//
using System;
using System.Text;
using System.Security.Cryptography;
using System.Reflection;
namespace ConsoleApplication1
{
class Program
{
public static string ComputeHash(
string str, // 要哈希的字符串
string hashType, // 哈希的类型SHA1、MD5
string encodeType // 编码模式ASCII、UTF8、
// 如果为null将采用Default编码
)
{
encodeType = string.IsNullOrEmpty(encodeType) ?
"Default" : encodeType.Trim();
string []assemblyName = new string[2] {
"System.Security.Cryptography." +
hashType.Trim().ToUpper() +
"CryptoServiceProvider",
"System.Text.Encoding"};
using (HashAlgorithm
Csp = Assembly.GetAssembly(
System.Type.GetType(assemblyName[0]))
.CreateInstance(assemblyName[0]) as HashAlgorithm)
{
str = Convert.ToBase64String(
Csp.ComputeHash(
(System.Type.GetType(assemblyName[1])
.GetProperty(encodeType)
.GetValue(null, null) as Encoding)
.GetBytes(str))
);
Csp.Clear();
}
return str;
}
static void Main(string[] args)
{
System.Console.WriteLine(
ComputeHash(@"http://wangye.org", "SHA1", "UTF8")
);
System.Console.WriteLine(
ComputeHash(@"http://wangye.org", "MD5", "UTF8")
);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment