MD5加密以及验证加密-加盐

加密与解密算法:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
/// <summary>
/// 签名字符串 32位
/// </summary>
/// <param name="input">要加密的字符串</param>
/// <param name="Key">加盐值</param>
/// <returns></returns>
public static string Sign(string prestr, string Key)
{
    System.Security.Cryptography.MD5 md5 = System.Security.Cryptography.MD5.Create();
    prestr = prestr + Key;
    byte[] data = md5.ComputeHash(System.Text.Encoding.Default.GetBytes(prestr));
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < data.Length; i++)
    {
        sb.Append(data[i].ToString("x2"));
    }
    return sb.ToString();
}
 
/// <summary>
/// 验证签名
/// </summary>
/// <param name="prestr">需要签名的字符串</param>
/// <param name="sign">签名结果(MD5加密过后的字符串)</param>
/// <param name="key">密钥</param>
/// <param name="_input_charset">编码格式</param>
/// <returns>验证结果</returns>
public static bool Verify(string prestr, string sign, string key)
{
    string mysign = Sign(prestr, key);
    if (mysign == sign)
    {
        return true;
    }
    else
    {
        return false;
    }
}

  

 

控制台调用:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
static void Main(string[] args)
{
    //密钥
    string Key = ",.huangfu/?";
 
    //原始密码
    string Prestr = "huangfu";
 
    //显示密钥与原始密码
    Console.WriteLine("原始密码:"+Prestr+"\n密钥是:"+Key);
 
    //加密原始密码
    string MD5Prestr = MD5.Sign(Prestr, Key);
 
    //输出加密过后的密码
    Console.WriteLine("经过MD5加密过后的字符串:" + MD5Prestr);
 
    //提示输入密码
    Console.WriteLine("请输入密码:");
    string PassWord = Convert.ToString(Console.ReadLine());
 
    //判断所输入密码是否与原始密码相同
    if (MD5.Verify(PassWord, MD5Prestr, Key))
        Console.WriteLine("密码正确!");
    else
        Console.WriteLine("密码错误!");
 
    Console.ReadKey();
}

  

 

输出结果:

posted on   ultrastrong  阅读(1329)  评论(0编辑  收藏  举报

努力加载评论中...
点击右上角即可分享
微信分享提示