现在的位置: 首页 > 综合 > 正文

C# 中使用 MD5 算法计算 hash (哈希)值的四种方法

2012年08月24日 ⁄ 综合 ⁄ 共 3308字 ⁄ 字号 评论关闭

计算哈希值

可以使用 System.Security.Cryptography 名称空间中包含的加密资源方便地生成和比较哈希值。 因为所有哈希函数的输入类型都是 Byte[],所以必须先将源数据转换为字节数组后再计算哈希值。 若要为一个字符串值创建哈希值,请按照下列步骤操作:

  1. 打开 Visual Studio .NET。
  2. 在 Microsoft C# 中新建控制台应用程序。Visual C# .NET 为您创建一个公用类以及一个空的 Main() 方法。
  3. SystemSystem.Security.Cryptography System.Text 名称空间使用 using 指令,这样,在后面的代码中就不需要限定这些名称空间中的声明了。这些语句必须放在所有其他声明之前。
    using System;
    using System.Security.Cryptography;
    using System.Text;

  4. 声明一个字符串变量以存放源数据,并声明两个字节数组(未定义大小)分别存放源字节和得出的哈希值。
    string sSourceData;
    byte[] tmpSource;
    byte[] tmpHash;

  5. 使用 GetBytes() 方法(它是 System.Text.ASCIIEncoding 类的成员)将源字符串转换为字节数组(这是哈希函数要求的输入类型)。
    sSourceData = "MySourceData";
    //Create a byte array from source data.
    tmpSource = ASCIIEncoding.ASCII.GetBytes(sSourceData);

  6. 通过在 MD5CryptoServiceProvider 类的一个实例上调用 ComputeHash 方法,来计算源数据的 MD5 哈希值。 注意,若要计算另一哈希值,需要另创建一个该类的实例。
    //Compute hash based on source data.
    tmpHash = new MD5CryptoServiceProvider().ComputeHash(tmpSource);

  7. 此时,tmpHash 字节数组中存放了计算源数据得出的哈希值(128 位值 = 16 个字节)。 通常,将此类值显示或存储为一个十六进制字符串是非常有用的,如以下代码所示:
    Console.WriteLine(ByteArrayToString(tmpHash));
    static string ByteArrayToString(byte[] arrInput)
    {
    	int i;
    	StringBuilder sOutput = new StringBuilder(arrInput.Length);
    	for (i=0;i < arrInput.Length -1; i++) 
    	{
    		sOutput.Append(arrInput[i].ToString("X2"));
    	}
    	return sOutput.ToString();
    }

  8. 保存并运行代码,以查看计算源数值得出的十六进制字符串。

比较两个哈希值

从源数据创建哈希值的目的之一是,提供一种方法查看数据经过一段时间后是否会发生改变,或者在不使用实际值的情况下比较两个值。 两种情况都需要比较两个哈希计算值,如果两个值都存储为十六进制字符串,则比较起来非常方便(如上一节中的最后一步所示)。 但是,两个值很有可能都采用字节数组的形式。 以下代码(继上一节中创建的代码)演示了如何比较两个字节数组。

  1. 创建完十六进制字符串后,紧接着基于新的源数据创建一个新的哈希值。

    sSourceData = "NotMySourceData";
    tmpSource = ASCIIEncoding.ASCII.GetBytes(sSourceData);
    
    byte[] tmpNewHash;
    		
    tmpNewHash = new MD5CryptoServiceProvider().ComputeHash(tmpSource);

  2. 比较两个字节数组的最直接的方法是,使用循环语句逐一比较两个值中对应的数组元素。 如果任何元素不同,或者两个数组的长度不同,则两个值不相等。
    bool bEqual = false;
    if (tmpNewHash.Length == tmpHash.Length)
    {
    	int i=0;
    	while ((i < tmpNewHash.Length) && (tmpNewHash[i] == tmpHash[i]))
    	{
    		i += 1;
    	}
    	if (i == tmpNewHash.Length) 
    	{
    		bEqual = true;
    	}
    }
    
    if (bEqual)
        Console.WriteLine("The two hash values are the same");
    else
        Console.WriteLine("The two hash values are not the same");
    Console.ReadLine();

  3. 保存并运行项目,查看从第一个哈希值创建的十六进制字符串,然后检查新的哈希值与原值是否相等。

-__________________________________________________________________________
在.net中,由 System.Security.Cryptography 命名空间提供了加密和哈希的几个类。其中 md5 编码由 MD5CryptoServiceProvider 实现。
在使用过程中由于 MD5CryptoServiceProvider 提供了多种方法去计算md5的hash值,反而令人搞不清楚,所以这里帖出计算md5的几种常见方法

先引用命名空间:

using System.Security.Cryptography;
using System.Text;

然后:

MD5CryptoServiceProvider md5=new MD5CryptoServiceProvider();

string source="HelloWorld";
byte[] message;
message=Encoding.Default.GetBytes(source);

//方法1
//  使用ComputeHash方法,适合用于计算简单的字符串的md5值时
md5.ComputeHash(message);
Console.WriteLine(Convert.ToBase64String(md5.Hash));

//方法2
//  使用TransformFinalBlock方法,适合用于原始数据不多时
md5.Initialize();
md5.TransformFinalBlock(message,0,message.Length);
Console.WriteLine(Convert.ToBase64String(md5.Hash));

//方法3
//  此方法等同于方法2
md5.Initialize();
md5.TransformBlock(message,0,message.Length,
     message,0); //note: output bytes must equal input bytes
md5.TransformFinalBlock(message,0,0);
Console.WriteLine(Convert.ToBase64String(md5.Hash));

//方法4
//  将原始消息分两次编码,得出的结果跟上面的一样,适合用于计算大量原始数据时,例如计算一个文件的md5值
md5.Initialize();
message=Encoding.Default.GetBytes("Hello");
md5.TransformBlock(message,0,message.Length,
     message,0);

message=Encoding.Default.GetBytes("World");
md5.TransformFinalBlock(message,0,message.Length);
Console.WriteLine(Convert.ToBase64String(md5.Hash));

 

抱歉!评论已关闭.