.NET中的加密算法总结(上)

发表于:2011-10-10 10:06

字体: | 上一篇 | 下一篇 | 我要投稿

 作者:JK_Rush(cnblogs)    来源:51Testing软件测试网采编

  如果信息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);
}

42/4<1234>
《2023软件测试行业现状调查报告》独家发布~

关注51Testing

联系我们

快捷面板 站点地图 联系我们 广告服务 关于我们 站长统计 发展历程

法律顾问:上海兰迪律师事务所 项棋律师
版权所有 上海博为峰软件技术股份有限公司 Copyright©51testing.com 2003-2024
投诉及意见反馈:webmaster@51testing.com; 业务联系:service@51testing.com 021-64471599-8017

沪ICP备05003035号

沪公网安备 31010102002173号