ASP.NET 中实现 MD5_HMAC(C#)

1@ Page Language="C#" Description="MD5_HMAC ASP.NET" 
1@ Import Namespace="System"
1@ Import Namespace="System.IO"
1@ Import Namespace="System.Security"
1@ Import Namespace="System.Security.Cryptography"
1@ Import Namespace="System.Text"
 1<script language="c#" runat="server">   
 2//by skyonline   
 3//Date: 2003/6/3   
 4//MD5 Function   
 5string fun_MD5(string str)   
 6{   
 7byte[] b = System.Text.Encoding.GetEncoding(1252).GetBytes(str);   
 8b=new System.Security.Cryptography.MD5CryptoServiceProvider().ComputeHash(b);   
 9string ret="";   
10for(int i=0;i<b.Length;i++)   
11ret+=b[i].ToString("x").PadLeft(2,'0');   
12return ret;   
13} 
14
15Byte[] hexstr2array(string HexStr)   
16{   
17string HEX = "0123456789ABCDEF";   
18string str = HexStr.ToUpper();   
19int len = str.Length;   
20byte[] RetByte = new byte[len/2];   
21for(int i=0; i<len/2; i++)   
22{   
23int NumHigh = HEX.IndexOf(str[i*2]);   
24int NumLow = HEX.IndexOf(str[i*2+1]);   
25RetByte[i] = Convert.ToByte(NumHigh*16+NumLow);   
26}   
27return RetByte;   
28}   
29</script>
 1   
 2//these for MD5_HMAC   
 3string ipad="";   
 4string opad=""; 
 5
 6{   
 7for(int i=0; i<64; i++)   
 8{   
 9ipad += "6";   
10opad += "\\\";   
11}   
12}   
13  
14string Password= "Jefe";   
15int KLen = Password.Length;   
16string iResult = "";   
17{   
18for(int i = 0; i < 64; i++)   
19{   
20if(i < KLen)   
21iResult += Convert.ToChar(ipad[i] ^ Password[i]);   
22else   
23iResult += Convert.ToChar(ipad[i]);   
24}   
25}   
26iResult += "what do ya want for nothing?";   
27iResult = fun_MD5(iResult);   
28  
29byte[] Test = hexstr2array(iResult);   
30iResult = "";   
31char[] b = System.Text.Encoding.GetEncoding(1252).GetChars(Test); 
32
33for(int i=0;i

<b.length;i++) (i="" (int="" +="&lt;br&gt; Congratulations! ::: " +result;="" ;="" <="" <html="" ^="" ```="" else="" for="" i="0;" i++)="" i<64;="" if="" iresult="" klen)="" message.text="" oresult="" password[i]);="" result="fun_MD5(oResult).ToUpper();" string="" {="" }="">


PS:希望对大家有帮助

如果要转载,请通知原作者:Email: [email protected]

//附:RFC2104

HMAC的定义。
定义HMAC需要一个加密用散列函数(表示为H)和一个密钥K。我们假设H是
一个将数据块用一个基本的迭代压缩函数来加密的散列函数。我们用B来表示数据块
的字长。(以上说提到的散列函数的分割数据块字长B=64),用L来表示散列函数的
输出数据字长(MD5中L=16,SHA—1中L=20)。鉴别密钥的长度可以是小于等于数
据块字长的任何正整数值。应用程序中使用的密钥长度若是比B大,则首先用使用散列
函数H作用于它,然后用H输出的L长度字符串作为在HMAC中实际使用的密钥。
一般情况下,推荐的最小密钥K长度是L个字长。(与H的输出数据长度相等)。更详
细的信息参见第三部分。
我们将定义两个固定且不同的字符串ipad,opad:
(‘i','o'标志内部与外部)
ipad = the byte 0x36 repeated B times
opad = the byte 0x5C repeated B times.
计算‘text'的HMAC:
H( K XOR opad, H(K XOR ipad, text))
即为以下步骤:

(1) 在密钥K后面添加0来创建一个子长为B的字符串。(例如,如果K的字长是20
字节,B=60字节,则K后会加入44个零字节0x00)

(2) 将上一步生成的B字长的字符串与ipad做异或运算。

(3) 将数据流text填充至第二步的结果字符串中。

(4) 用H作用于第三步生成的数据流。

(5) 将第一步生成的B字长字符串与opad做异或运算。

(6) 再将第四步的结果填充进第五步的结果中。

(7) 用H作用于第六步生成的数据流,输出最终结果</b.length;i++)>

Published At
Categories with Web编程
Tagged with
comments powered by Disqus