
/*

* 哈希算法MD5和SHA1的C#实现

*

*

* 夏春涛 Email:xChuntao@163.com

* Blog:http://bluesky521.cnblogs.com

* 运行环境:.net2.0 framework

*/


/*

* 关于哈希函数:

* 哈希函数将任意长度的二进制字符串映射为固定长度的小型二进制字符串。

* 加密哈希函数有这样一个属性:在计算上不大可能找到散列为相同的值的两个

* 不同的输入;也就是说,两组数据的哈希值仅在对应的数据也匹配时才会匹配。

* 数据的少量更改会在哈希值中产生不可预知的大量更改。

*

* MD5 算法的哈希值大小为 128 位。

* SHA1 算法的哈希值大小为 160 位。

*/


using System;

using System.Collections.Generic;

using System.Text;

using System.Security.Cryptography;


namespace MD5_App

{

class Program

{

static void Main(string[] args)

{

string strSrc = "How are you?";

Console.WriteLine("原文:" + strSrc);

Console.WriteLine();


Console.WriteLine("MD5哈希值:" + MD5_Hash(strSrc));

Console.WriteLine();


Console.WriteLine("SHA1哈希值:" + SHA1_Hash(strSrc));

Console.WriteLine();

}


//MD5

static public string MD5_Hash(string str_md5_in)

{

MD5 md5 = new MD5CryptoServiceProvider();

byte[] bytes_md5_in = UTF8Encoding.Default.GetBytes(str_md5_in);

byte[] bytes_md5_out = md5.ComputeHash(bytes_md5_in);

string str_md5_out = BitConverter.ToString(bytes_md5_out);

//str_md5_out = str_md5_out.Replace("-", "");

return str_md5_out;

}


//SHA1

static public string SHA1_Hash(string str_sha1_in)

{

SHA1 sha1 = new SHA1CryptoServiceProvider();

byte[] bytes_sha1_in = UTF8Encoding.Default.GetBytes(str_sha1_in);

byte[] bytes_sha1_out = sha1.ComputeHash(bytes_sha1_in);

string str_sha1_out = BitConverter.ToString(bytes_sha1_out);

//str_sha1_out = str_sha1_out.Replace("-", "");

return str_sha1_out;

}

}

}