您的位置:首页 > 编程语言 > C#

HMAC-MD5的C#实现

2005-12-01 11:35 211 查看
由于工作的需要,编写了一个C#版本的HMAC-MD5加密算法。


/**
*
* hmac_md5口令加密算法
*
*/
public byte[] hmac_md5(string timespan, string password)
{
byte[] b_tmp;
byte[] b_tmp1;
if (password == null)
{
return null;
}
byte[] digest = new byte[512];
byte[] k_ipad = new byte[64];
byte[] k_opad = new byte[64];
byte[] source = System.Text.ASCIIEncoding.ASCII.GetBytes(password);
System.Security.Cryptography.MD5 shainner = new MD5CryptoServiceProvider();
for (int i = 0; i < 64; i++)
{
k_ipad[i] = 0 ^ 0x36;
k_opad[i] = 0 ^ 0x5c;
}
try
{
if (source.Length > 64)
{
shainner = new MD5CryptoServiceProvider();
source = shainner.ComputeHash(source);
}
for (int i = 0; i < source.Length; i++)
{
k_ipad[i] = (byte) (source[i] ^ 0x36);
k_opad[i] = (byte) (source[i] ^ 0x5c);
}
b_tmp1 = System.Text.ASCIIEncoding.ASCII.GetBytes(timespan);
b_tmp = adding(k_ipad,b_tmp1);
shainner = new MD5CryptoServiceProvider();
digest = shainner.ComputeHash(b_tmp);
b_tmp = adding(k_opad,digest);
shainner = new MD5CryptoServiceProvider();
digest = shainner.ComputeHash(b_tmp);
return digest;
}
catch (Exception e)
{
throw e;
}
}
/**
*
* 填充byte
*
*/
public byte[] adding(byte[] a,byte[] b)
{
byte[] c = new byte[a.Length+b.Length];
a.CopyTo(c,0);
b.CopyTo(c,a.Length);
return c;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: