如果信息m1=m2那么,那么将得到同一的哈希地址,但是信息m1!=m2也可能得到同一哈希地址,那么就发生了哈希冲突(collision),在一般的情况下,哈希冲突只能尽可能地减少,而不能完全避免。当发生哈希冲突时,我们要使用冲突解决方法,而主要的冲突解决方法:开放地址法、再哈希法、链地址法和建立一个公共溢出区。
图4 Hash加密过程
现在让我们来实现通用的hash加密方法。
/// <summary> /// Encrypts the specified hash algorithm. /// 1. Generates a cryptographic Hash Key for the provided text data. /// </summary> /// <param name="hashAlgorithm">The hash algorithm.</param> /// <param name="dataToHash">The data to hash.</param> /// <returns></returns> public static string Encrypt(HashAlgorithm hashAlgorithm, string dataToHash) { var tabStringHex = new string[16]; var UTF8 = new System.Text.UTF8Encoding(); byte[] data = UTF8.GetBytes(dataToHash); byte[] result = hashAlgorithm.ComputeHash(data); var hexResult = new StringBuilder(result.Length); for (int i = 0; i < result.Length; i++) { //// Convert to hexadecimal hexResult.Append(result[i].ToString("X2")); } return hexResult.ToString(); } |
上面的加密方法包含一个HashAlgorithm类型的参数,我们可以传递继承于抽象类HashAlgorithm的具体hash算法(MD5,SHA1和SHA256等),通过继承多态性我们使得加密方法更加灵活、简单,最重要的是现在我们只需维护一个通用的加密方法就OK了。
接着我们要添加判断加密后哈希值是否相等的方法,判断哈希值是否相等的方法IsHashMatch()方法。
/// <summary> /// Determines whether [is hash match] [the specified hash algorithm]. /// </summary> /// <param name="hashAlgorithm">The hash algorithm.</param> /// <param name="hashedText">The hashed text.</param> /// <param name="unhashedText">The unhashed text.</param> /// <returns> /// <c>true</c> if [is hash match] [the specified hash algorithm]; /// otherwise, <c>false</c>. /// </returns> public static bool IsHashMatch(HashAlgorithm hashAlgorithm, string hashedText, string unhashedText) { string hashedTextToCompare = Encrypt( hashAlgorithm, unhashedText); return (String.Compare(hashedText, hashedTextToCompare, false) == 0); } |