标签:
已做修改
一、关于本文
本文中是一个类库,包括下面几个函数:
/// 1)计算32位MD5码(大小写):Hash_MD5_32 /// 2)计算16位MD5码(大小写):Hash_MD5_16 /// 3)计算32位2重MD5码(大小写):Hash_2_MD5_32 /// 4)计算16位2重MD5码(大小写):Hash_2_MD5_16 /// 5)计算SHA-1码(大小写):Hash_SHA_1 /// 6)计算SHA-256码(大小写):Hash_SHA_256 /// 7)计算SHA-384码(大小写):Hash_SHA_384 /// 8)计算SHA-512码(大小写):Hash_SHA_512 /// 9)计算文件的 SHA256 值:SHA256File /// 10)计算文件的 MD5 值:MD5File /// 11)计算文件的 SHA1 值:SHA1File
编译后被打包成文件HashTools.dll,其他程序可以在添加引用后对这些函数进行调用
二、类库中各函数代码
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace HashTool { /// <summary> /// C# 计算字符串/文件哈希值(MD5、SHA) /// 1)计算32位MD5码(大小写):Hash_MD5_32 /// 2)计算16位MD5码(大小写):Hash_MD5_16 /// 3)计算32位2重MD5码(大小写):Hash_2_MD5_32 /// 4)计算16位2重MD5码(大小写):Hash_2_MD5_16 /// 5)计算SHA-1码(大小写):Hash_SHA_1 /// 6)计算SHA-256码(大小写):Hash_SHA_256 /// 7)计算SHA-384码(大小写):Hash_SHA_384 /// 8)计算SHA-512码(大小写):Hash_SHA_512 /// 9)计算文件的 SHA256 值:SHA256File /// 10)计算文件的 MD5 值:MD5File /// 11)计算文件的 SHA1 值:SHA1File /// </summary> public class HashHelper { /// <summary> /// 计算32位MD5码 /// </summary> /// <param name="word">字符串</param> /// <param name="toUpper">返回哈希值格式 true:英文大写,false:英文小写</param> /// <returns></returns> public static string Hash_MD5_32(string word, bool toUpper = true) { try { System.Security.Cryptography.MD5CryptoServiceProvider MD5CSP = new System.Security.Cryptography.MD5CryptoServiceProvider(); byte[] bytValue = System.Text.Encoding.UTF8.GetBytes(word); byte[] bytHash = MD5CSP.ComputeHash(bytValue); MD5CSP.Clear(); //根据计算得到的Hash码翻译为MD5码 string sHash = "", sTemp = ""; for (int counter = 0; counter < bytHash.Count(); counter++) { long i = bytHash[counter] / 16; if (i > 9) { sTemp = ((char)(i - 10 + 0x41)).ToString(); } else { sTemp = ((char)(i + 0x30)).ToString(); } i = bytHash[counter] % 16; if (i > 9) { sTemp += ((char)(i - 10 + 0x41)).ToString(); } else { sTemp += ((char)(i + 0x30)).ToString(); } sHash += sTemp; } //根据大小写规则决定返回的字符串 return toUpper ? sHash : sHash.ToLower(); } catch (Exception ex) { throw new Exception(ex.Message); } } /// <summary> /// 计算16位MD5码 /// </summary> /// <param name="word">字符串</param> /// <param name="toUpper">返回哈希值格式 true:英文大写,false:英文小写</param> /// <returns></returns> public static string Hash_MD5_16(string word, bool toUpper = true) { try { string sHash = Hash_MD5_32(word).Substring(8, 16); return toUpper ? sHash : sHash.ToLower(); } catch (Exception ex) { throw new Exception(ex.Message); } } /// <summary> /// 计算32位2重MD5码 /// </summary> /// <param name="word">字符串</param> /// <param name="toUpper">返回哈希值格式 true:英文大写,false:英文小写</param> /// <returns></returns> public static string Hash_2_MD5_32(string word, bool toUpper = true) { try { System.Security.Cryptography.MD5CryptoServiceProvider MD5CSP = new System.Security.Cryptography.MD5CryptoServiceProvider(); byte[] bytValue = System.Text.Encoding.UTF8.GetBytes(word); byte[] bytHash = MD5CSP.ComputeHash(bytValue); //根据计算得到的Hash码翻译为MD5码 string sHash = "", sTemp = ""; for (int counter = 0; counter < bytHash.Count(); counter++) { long i = bytHash[counter] / 16; if (i > 9) { sTemp = ((char)(i - 10 + 0x41)).ToString(); } else { sTemp = ((char)(i + 0x30)).ToString(); } i = bytHash[counter] % 16; if (i > 9) { sTemp += ((char)(i - 10 + 0x41)).ToString(); } else { sTemp += ((char)(i + 0x30)).ToString(); } sHash += sTemp; } bytValue = System.Text.Encoding.UTF8.GetBytes(sHash); bytHash = MD5CSP.ComputeHash(bytValue); MD5CSP.Clear(); sHash = ""; //根据计算得到的Hash码翻译为MD5码 for (int counter = 0; counter < bytHash.Count(); counter++) { long i = bytHash[counter] / 16; if (i > 9) { sTemp = ((char)(i - 10 + 0x41)).ToString(); } else { sTemp = ((char)(i + 0x30)).ToString(); } i = bytHash[counter] % 16; if (i > 9) { sTemp += ((char)(i - 10 + 0x41)).ToString(); } else { sTemp += ((char)(i + 0x30)).ToString(); } sHash += sTemp; } //根据大小写规则决定返回的字符串 return toUpper ? sHash : sHash.ToLower(); } catch (Exception ex) { throw new Exception(ex.Message); } } /// <summary> /// 计算16位2重MD5码 /// </summary> /// <param name="word">字符串</param> /// <param name="toUpper">返回哈希值格式 true:英文大写,false:英文小写</param> /// <returns></returns> public static string Hash_2_MD5_16(string word, bool toUpper = true) { try { System.Security.Cryptography.MD5CryptoServiceProvider MD5CSP = new System.Security.Cryptography.MD5CryptoServiceProvider(); byte[] bytValue = System.Text.Encoding.UTF8.GetBytes(word); byte[] bytHash = MD5CSP.ComputeHash(bytValue); //根据计算得到的Hash码翻译为MD5码 string sHash = "", sTemp = ""; for (int counter = 0; counter < bytHash.Count(); counter++) { long i = bytHash[counter] / 16; if (i > 9) { sTemp = ((char)(i - 10 + 0x41)).ToString(); } else { sTemp = ((char)(i + 0x30)).ToString(); } i = bytHash[counter] % 16; if (i > 9) { sTemp += ((char)(i - 10 + 0x41)).ToString(); } else { sTemp += ((char)(i + 0x30)).ToString(); } sHash += sTemp; } sHash = sHash.Substring(8, 16); bytValue = System.Text.Encoding.UTF8.GetBytes(sHash); bytHash = MD5CSP.ComputeHash(bytValue); MD5CSP.Clear(); sHash = ""; //根据计算得到的Hash码翻译为MD5码 for (int counter = 0; counter < bytHash.Count(); counter++) { long i = bytHash[counter] / 16; if (i > 9) { sTemp = ((char)(i - 10 + 0x41)).ToString(); } else { sTemp = ((char)(i + 0x30)).ToString(); } i = bytHash[counter] % 16; if (i > 9) { sTemp += ((char)(i - 10 + 0x41)).ToString(); } else { sTemp += ((char)(i + 0x30)).ToString(); } sHash += sTemp; } sHash = sHash.Substring(8, 16); //根据大小写规则决定返回的字符串 return toUpper ? sHash : sHash.ToLower(); } catch (Exception ex) { throw new Exception(ex.Message); } } /// <summary> /// 计算SHA-1码 /// </summary> /// <param name="word">字符串</param> /// <param name="toUpper">返回哈希值格式 true:英文大写,false:英文小写</param> /// <returns></returns> public static string Hash_SHA_1(string word, bool toUpper = true) { try { System.Security.Cryptography.SHA1CryptoServiceProvider SHA1CSP = new System.Security.Cryptography.SHA1CryptoServiceProvider(); byte[] bytValue = System.Text.Encoding.UTF8.GetBytes(word); byte[] bytHash = SHA1CSP.ComputeHash(bytValue); SHA1CSP.Clear(); //根据计算得到的Hash码翻译为SHA-1码 string sHash = "", sTemp = ""; for (int counter = 0; counter < bytHash.Count(); counter++) { long i = bytHash[counter] / 16; if (i > 9) { sTemp = ((char)(i - 10 + 0x41)).ToString(); } else { sTemp = ((char)(i + 0x30)).ToString(); } i = bytHash[counter] % 16; if (i > 9) { sTemp += ((char)(i - 10 + 0x41)).ToString(); } else { sTemp += ((char)(i + 0x30)).ToString(); } sHash += sTemp; } //根据大小写规则决定返回的字符串 return toUpper ? sHash : sHash.ToLower(); } catch (Exception ex) { throw new Exception(ex.Message); } } /// <summary> /// 计算SHA-256码 /// </summary> /// <param name="word">字符串</param> /// <param name="toUpper">返回哈希值格式 true:英文大写,false:英文小写</param> /// <returns></returns> public static string Hash_SHA_256(string word, bool toUpper = true) { try { System.Security.Cryptography.SHA256CryptoServiceProvider SHA256CSP = new System.Security.Cryptography.SHA256CryptoServiceProvider(); byte[] bytValue = System.Text.Encoding.UTF8.GetBytes(word); byte[] bytHash = SHA256CSP.ComputeHash(bytValue); SHA256CSP.Clear(); //根据计算得到的Hash码翻译为SHA-1码 string sHash = "", sTemp = ""; for (int counter = 0; counter < bytHash.Count(); counter++) { long i = bytHash[counter] / 16; if (i > 9) { sTemp = ((char)(i - 10 + 0x41)).ToString(); } else { sTemp = ((char)(i + 0x30)).ToString(); } i = bytHash[counter] % 16; if (i > 9) { sTemp += ((char)(i - 10 + 0x41)).ToString(); } else { sTemp += ((char)(i + 0x30)).ToString(); } sHash += sTemp; } //根据大小写规则决定返回的字符串 return toUpper ? sHash : sHash.ToLower(); } catch (Exception ex) { throw new Exception(ex.Message); } } /// <summary> /// 计算SHA-384码 /// </summary> /// <param name="word">字符串</param> /// <param name="toUpper">返回哈希值格式 true:英文大写,false:英文小写</param> /// <returns></returns> public static string Hash_SHA_384(string word, bool toUpper = true) { try { System.Security.Cryptography.SHA384CryptoServiceProvider SHA384CSP = new System.Security.Cryptography.SHA384CryptoServiceProvider(); byte[] bytValue = System.Text.Encoding.UTF8.GetBytes(word); byte[] bytHash = SHA384CSP.ComputeHash(bytValue); SHA384CSP.Clear(); //根据计算得到的Hash码翻译为SHA-1码 string sHash = "", sTemp = ""; for (int counter = 0; counter < bytHash.Count(); counter++) { long i = bytHash[counter] / 16; if (i > 9) { sTemp = ((char)(i - 10 + 0x41)).ToString(); } else { sTemp = ((char)(i + 0x30)).ToString(); } i = bytHash[counter] % 16; if (i > 9) { sTemp += ((char)(i - 10 + 0x41)).ToString(); } else { sTemp += ((char)(i + 0x30)).ToString(); } sHash += sTemp; } //根据大小写规则决定返回的字符串 return toUpper ? sHash : sHash.ToLower(); } catch (Exception ex) { throw new Exception(ex.Message); } } /// <summary> /// 计算SHA-512码 /// </summary> /// <param name="word">字符串</param> /// <param name="toUpper">返回哈希值格式 true:英文大写,false:英文小写</param> /// <returns></returns> public static string Hash_SHA_512(string word, bool toUpper = true) { try { System.Security.Cryptography.SHA512CryptoServiceProvider SHA512CSP = new System.Security.Cryptography.SHA512CryptoServiceProvider(); byte[] bytValue = System.Text.Encoding.UTF8.GetBytes(word); byte[] bytHash = SHA512CSP.ComputeHash(bytValue); SHA512CSP.Clear(); //根据计算得到的Hash码翻译为SHA-1码 string sHash = "", sTemp = ""; for (int counter = 0; counter < bytHash.Count(); counter++) { long i = bytHash[counter] / 16; if (i > 9) { sTemp = ((char)(i - 10 + 0x41)).ToString(); } else { sTemp = ((char)(i + 0x30)).ToString(); } i = bytHash[counter] % 16; if (i > 9) { sTemp += ((char)(i - 10 + 0x41)).ToString(); } else { sTemp += ((char)(i + 0x30)).ToString(); } sHash += sTemp; } //根据大小写规则决定返回的字符串 return toUpper ? sHash : sHash.ToLower(); } catch (Exception ex) { throw new Exception(ex.Message); } } /// <summary> /// 计算文件的 SHA256 值 /// </summary> /// <param name="fileStream">文件流</param> /// <returns>System.String.</returns> public static string SHA256File(System.IO.FileStream fileStream) { System.Security.Cryptography.SHA256 mySHA256 = System.Security.Cryptography.SHA256Managed.Create(); byte[] hashValue; // Create a fileStream for the file. //FileStream fileStream = fInfo.Open(FileMode.Open); // Be sure it‘s positioned to the beginning of the stream. fileStream.Position = 0; // Compute the hash of the fileStream. hashValue = mySHA256.ComputeHash(fileStream); // Close the file. fileStream.Close(); // Write the hash value to the Console. return PrintByteArray(hashValue); } /// <summary> /// 计算文件的 MD5 值 /// </summary> /// <param name="fileName">要计算 MD5 值的文件名和路径</param> /// <returns>MD5 值16进制字符串</returns> public static string MD5File(string fileName) { return HashFile(fileName, "md5"); } /// <summary> /// 计算文件的 sha1 值 /// </summary> /// <param name="fileName">要计算 sha1 值的文件名和路径</param> /// <returns>sha1 值16进制字符串</returns> public static string SHA1File(string fileName) { return HashFile(fileName, "sha1"); } /// <summary> /// 计算文件的哈希值 /// </summary> /// <param name="fileName">要计算哈希值的文件名和路径</param> /// <param name="algName">算法:sha1,md5</param> /// <returns>哈希值16进制字符串</returns> private static string HashFile(string fileName, string algName) { if (!System.IO.File.Exists(fileName)) return string.Empty; System.IO.FileStream fs = new System.IO.FileStream(fileName, System.IO.FileMode.Open, System.IO.FileAccess.Read); byte[] hashBytes = HashData(fs, algName); fs.Close(); return ByteArrayToHexString(hashBytes); } /// <summary> /// 计算哈希值 /// </summary> /// <param name="stream">要计算哈希值的 Stream</param> /// <param name="algName">算法:sha1,md5</param> /// <returns>哈希值字节数组</returns> private static byte[] HashData(System.IO.Stream stream, string algName) { System.Security.Cryptography.HashAlgorithm algorithm; if (algName == null) { throw new ArgumentNullException("algName 不能为 null"); } if (string.Compare(algName, "sha1", true) == 0) { algorithm = System.Security.Cryptography.SHA1.Create(); } else { if (string.Compare(algName, "md5", true) != 0) { throw new Exception("algName 只能使用 sha1 或 md5"); } algorithm = System.Security.Cryptography.MD5.Create(); } return algorithm.ComputeHash(stream); } /// <summary> /// 字节数组转换为16进制表示的字符串 /// </summary> private static string ByteArrayToHexString(byte[] buf) { return BitConverter.ToString(buf).Replace("-", ""); } private static string PrintByteArray(byte[] array) { StringBuilder sb = new StringBuilder(); int i; for (i = 0; i < array.Length; i++) { sb.Append(String.Format("{0:X2}", array[i])); } return sb.ToString(); } /// <summary> /// 计算指定文件的CRC32值 /// </summary> /// <param name="fileName">指定文件的完全限定名称</param> /// <returns>返回值的字符串形式</returns> public static String Crc32File(String fileName) { String hashCRC32 = String.Empty; //检查文件是否存在,如果文件存在则进行计算,否则返回空值 if (System.IO.File.Exists(fileName)) { using (System.IO.FileStream fs = new System.IO.FileStream(fileName, System.IO.FileMode.Open, System.IO.FileAccess.Read)) { //计算文件的CSC32值 Crc32 calculator = new Crc32(); Byte[] buffer = calculator.ComputeHash(fs); calculator.Clear(); //将字节数组转换成十六进制的字符串形式 StringBuilder stringBuilder = new StringBuilder(); for (int i = 0; i < buffer.Length; i++) { stringBuilder.Append(buffer[i].ToString("X2")); } hashCRC32 = stringBuilder.ToString(); }//关闭文件流 } return hashCRC32; } #region Class CRC32 算法的实现 /// <summary> /// 提供 CRC32 算法的实现 /// </summary> private class Crc32 : System.Security.Cryptography.HashAlgorithm { public const UInt32 DefaultPolynomial = 0xedb88320; public const UInt32 DefaultSeed = 0xffffffff; private UInt32 hash; private UInt32 seed; private UInt32[] table; private static UInt32[] defaultTable; public Crc32() { table = InitializeTable(DefaultPolynomial); seed = DefaultSeed; Initialize(); } public Crc32(UInt32 polynomial, UInt32 seed) { table = InitializeTable(polynomial); this.seed = seed; Initialize(); } public override void Initialize() { hash = seed; } protected override void HashCore(byte[] buffer, int start, int length) { hash = CalculateHash(table, hash, buffer, start, length); } protected override byte[] HashFinal() { byte[] hashBuffer = UInt32ToBigEndianBytes(~hash); this.HashValue = hashBuffer; return hashBuffer; } public static UInt32 Compute(byte[] buffer) { return ~CalculateHash(InitializeTable(DefaultPolynomial), DefaultSeed, buffer, 0, buffer.Length); } public static UInt32 Compute(UInt32 seed, byte[] buffer) { return ~CalculateHash(InitializeTable(DefaultPolynomial), seed, buffer, 0, buffer.Length); } public static UInt32 Compute(UInt32 polynomial, UInt32 seed, byte[] buffer) { return ~CalculateHash(InitializeTable(polynomial), seed, buffer, 0, buffer.Length); } private static UInt32[] InitializeTable(UInt32 polynomial) { if (polynomial == DefaultPolynomial && defaultTable != null) { return defaultTable; } UInt32[] createTable = new UInt32[256]; for (int i = 0; i < 256; i++) { UInt32 entry = (UInt32)i; for (int j = 0; j < 8; j++) { if ((entry & 1) == 1) entry = (entry >> 1) ^ polynomial; else entry = entry >> 1; } createTable[i] = entry; } if (polynomial == DefaultPolynomial) { defaultTable = createTable; } return createTable; } private static UInt32 CalculateHash(UInt32[] table, UInt32 seed, byte[] buffer, int start, int size) { UInt32 crc = seed; for (int i = start; i < size; i++) { unchecked { crc = (crc >> 8) ^ table[buffer[i] ^ crc & 0xff]; } } return crc; } private byte[] UInt32ToBigEndianBytes(UInt32 x) { return new byte[] { (byte)((x >> 24) & 0xff), (byte)((x >> 16) & 0xff), (byte)((x >> 8) & 0xff), (byte)(x & 0xff) }; } } #endregion } }
三、函数调用 建立项目ComputeHash,添加对HashTools.dll库的引用。并添加代码: using HashTools; 然后在Main函数中添加下列代码:
static void Main(string[] args) { Console.WriteLine("MD5 of \"abc\""); Console.WriteLine("MD5_32(Upper): {0}", HashHelper.Hash_MD5_32("abc")); Console.WriteLine("MD5_32(Lower): {0}", HashHelper.Hash_MD5_32("abc", false)); Console.WriteLine("MD5_16(Upper): {0}", HashHelper.Hash_MD5_16("abc")); Console.WriteLine("MD5_16(Lower): {0}", HashHelper.Hash_MD5_16("abc", false)); Console.WriteLine("2_MD5_32(Upper): {0}", HashHelper.Hash_2_MD5_32("abc")); Console.WriteLine("2_MD5_32(Lower): {0}", HashHelper.Hash_2_MD5_32("abc", false)); Console.WriteLine("2_MD5_32(Upper): {0}", HashHelper.Hash_2_MD5_16("abc")); Console.WriteLine("2_MD5_32(Lower): {0}", HashHelper.Hash_2_MD5_16("abc", false)); Console.WriteLine("SHA of \"abc\""); Console.WriteLine("SHA-1(Upper): {0}", HashHelper.Hash_SHA_1("abc")); Console.WriteLine("SHA-1(Lower): {0}", HashHelper.Hash_SHA_1("abc", false)); Console.WriteLine("SHA-256(Upper): {0}", HashHelper.Hash_SHA_256("abc")); Console.WriteLine("SHA-256(Lower): {0}", HashHelper.Hash_SHA_256("abc", false)); Console.WriteLine("SHA-384(Upper): {0}", HashHelper.Hash_SHA_384("abc")); Console.WriteLine("SHA-384(Lower): {0}", HashHelper.Hash_SHA_384("abc", false)); Console.WriteLine("SHA-512(Upper): {0}", HashHelper.Hash_SHA_512("abc")); Console.WriteLine("SHA-512(Lower): {0}", HashHelper.Hash_SHA_512("abc", false)); Console.ReadLine(); } 运行结果如下:
标签:
原文地址:http://www.cnblogs.com/lonelyxmas/p/4565180.html