- using System;
- using System.Security.Cryptography;
- using System.Text;
- namespace Hashing
- {
- class Class1
- {
- [STAThread]
- static void Main(string[] args)
- {
- string original = string.Empty;
- Console.WriteLine( "Enter something you want hashed: " );
- original = Console.ReadLine();
- foreach( HashType hashtype in Enum.GetValues( typeof(HashType)) )
- {
- try
- {
- string hash = HashManager.GetHash( original, hashtype );
- Console.WriteLine( "{0} hash for {1} is {3} characaters: {2}", hashtype, password, hash, hash.Length );
- }
- catch( Exception ex )
- {
- Console.WriteLine( "Unexpected {0}: {1}", ex.GetType().Name, ex.Message );
- }
- }
- Console.WriteLine();
- Console.WriteLine( "Press enter to continue..." );
- Console.ReadLine();
- }
- }
- public enum HashType : int { MD5, SHA1, SHA256, SHA384, SHA512 }
- public class HashManager
- {
- private HashManager() { }
- public static string GetHash( string original )
- {
- return GetHash( original, HashType.SHA512 );
- }
- public static string GetHash(string original, HashType hashType)
- {
- string hash;
- switch (hashType)
- {
- case HashType.MD5:
- hash = GetMD5Hash( original );
- break;
- case HashType.SHA1:
- hash = GetSHA1Hash( original );
- break;
- case HashType.SHA256:
- hash = GetSHA256Hash( original );
- break;
- case HashType.SHA384:
- hash = GetSHA384Hash( original );
- break;
- case HashType.SHA512:
- hash = GetSHA512Hash( original );
- break;
- default:
- throw new ArgumentOutOfRangeException( "hashType", hashType, "Unsupported HashType." );
- }
- return hash;
- }
- private static string GetMD5Hash( string original )
- {
- UnicodeEncoding UE = new UnicodeEncoding();
- byte[] HashValue, MessageBytes = UE.GetBytes( original );
- MD5 md5 = new MD5CryptoServiceProvider();
- string strHex = "";
- HashValue = md5.ComputeHash(MessageBytes);
- foreach(byte b in HashValue)
- {
- strHex += String.Format("{0:x2}", b);
- }
- return strHex;
- } /* GetMD5 */
- private static string GetSHA1Hash( string original )
- {
- UnicodeEncoding UE = new UnicodeEncoding();
- byte[] HashValue, MessageBytes = UE.GetBytes( original );
- SHA1Managed SHhash = new SHA1Managed();
- string strHex = "";
- HashValue = SHhash.ComputeHash(MessageBytes);
- foreach(byte b in HashValue)
- {
- strHex += String.Format("{0:x2}", b);
- }
- return strHex;
- } /* GetSHA1 */
- private static string GetSHA256Hash( string original )
- {
- UnicodeEncoding UE = new UnicodeEncoding();
- byte[] HashValue, MessageBytes = UE.GetBytes( original );
- SHA256Managed SHhash = new SHA256Managed();
- string strHex = "";
- HashValue = SHhash.ComputeHash(MessageBytes);
- foreach(byte b in HashValue)
- {
- strHex += String.Format("{0:x2}", b);
- }
- return strHex;
- } /* GetSHA256 */
- private static string GetSHA384Hash( string original )
- {
- UnicodeEncoding UE = new UnicodeEncoding();
- byte[
- //该片段来自于http://www.codesnippet.cn/detail/201220121100.html
来源: http://www.codesnippet.cn/detail/201220121100.html