C#哈希Md5加密

/// <param name="strSource">待加密字串</param>
/// <param name="length">16或32值之一,其它则采用.net默认MD5加密算法</param>
/// <returns>加密后的字串</returns>
public static string MD5Encrypt(string strSource, int length)
{
    byte[] bytes = Encoding.ASCII.GetBytes(strSource);
    byte[] hashValue = ((System.Security.Cryptography.HashAlgorithm)System.Security.Cryptography.CryptoConfig.CreateFromName("MD5")).ComputeHash(bytes);
    StringBuilder sb = new StringBuilder();
    switch (length)
    {
        case 16:
            for (int i = 4; i < 12; i++)
                sb.Append(hashValue[i].ToString("x2"));
            break;
        case 32:
            for (int i = 0; i < 16; i++)
            {
                sb.Append(hashValue[i].ToString("x2"));
            }
            break;
        default:
            for (int i = 0; i < hashValue.Length; i++)
            {
                sb.Append(hashValue[i].ToString("x2"));
            }
            break;
    }
    return sb.ToString();
}

public static string MSMD5(String str)
{
    MD5 md5 = new MD5CryptoServiceProvider();
    byte[] data = System.Text.Encoding.Default.GetBytes(str);
    byte[] result = md5.ComputeHash(data);
    String ret = "";
    for (int i = 0; i < result.Length; i++)
        ret += result[i].ToString("x").PadLeft(2, '0');
    return ret;
}


static string MSGetMd5Hash(string input)
{
    MD5 md5Hasher = System.Security.Cryptography.MD5.Create();
    byte[] data = md5Hasher.ComputeHash(Encoding.Default.GetBytes(input));
    StringBuilder sBuilder = new StringBuilder();
    for (int i = 0; i < data.Length; i++)
    {
        sBuilder.Append(data[i].ToString("x2"));
    }
    return sBuilder.ToString();
}

static bool VerifyMd5Hash(string input, string hash)
{
    string hashOfInput = MSGetMd5Hash(input);
    StringComparer comparer = StringComparer.OrdinalIgnoreCase;
    if (0 == comparer.Compare(hashOfInput, hash))
    {
        return true;
    }
    else
    {
        return false;
    }
}

 

=============================================


c#加密 可逆与不可逆MD5 加密

地址:http://www.cnblogs.com/sunmoonstarash/articles/1404624.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值