详解C#实现MD5加密的示例代码

2019-12-30 15:33:08王冬梅

二、首先在界面中引入:using System.Web.Security;

假设密码对话框名字password,对输入的密码加密后存入变量pwd中,语句如下:


 string pwd = FormsAuthentication.HashPasswordForStoringInConfigFile(password.Text, "MD5");

如果要录入则录入pwd,这样数据库实际的密码为202*****等乱码了。

如果登录查询则要:


select username,password from users where username='"+ UserName.Text +"' and password='"+ pwd +"'

因为MD5不能解密,只能把原始密码加密后与数据库中加密的密码比较

三、C# MD5 加密方法 16位或32位


 public string md5(string str,int code) 
 { 
  if(code==16) //16位MD5加密(取32位加密的9~25字符) 
  { 
    return System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(str,"MD5").ToLower().Substring(8,16) ; 
  } 
  else//32位加密 
  { 
    return System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(str,"MD5").ToLower(); 
  } 
 } 

四、做一个网站时,必然涉及用户登录,用户登录必然涉及密码,密码必然涉及安全,安全必然涉及加密。

加密现时最流行也是据说最安全的算法是MD5算法,MD5是一种不可逆的算法,也就是 明文经过加密后,根据加密过的密文无法还原出明文来。

目前有好多网站专搞MD5破密,百度上搜一下MD5就搜出一大堆了,今天早上无聊试了几个破密网站,6位以内纯数字密码的MD5密文可以还原出明文,长点的或带字符的就不行了。他们是采用穷举对比的,就是说把收录到的明文和密文放到数据库里,通过密文的对比来确定明文,毕竟收录的数据有限,所以破解的密码很有限。

扯远了,搞破密MD5需要大量的MONEY,因为要一个运算得超快的计算机和一个查找性能超好的数据库和超大的数据库收录。但搞加密就比较简单。以下是我用C#写的一个MD5加密的方法,用到.NET中的方法, 通过MD5_APP.StringToMD5(string str, int i)可以直接调用:


public class MD5_APP
{
 public MD5_APP()
 {
   
 }

  public static string StringToMD5(string str, int i)
  {
    //获取要加密的字段,并转化为Byte[]数组
    byte[] data = System.Text.Encoding.Unicode.GetBytes(str.ToCharArray());
    //建立加密服务
    System.Security.Cryptography.MD5 md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
    //加密Byte[]数组
    byte[] result = md5.ComputeHash(data);
    //将加密后的数组转化为字段
    if (i == 16 && str != string.Empty)
    {
      return System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(str, "MD5").ToLower().Substring(8, 16);
    }
    else if (i == 32 && str != string.Empty)
    {
      return System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(str, "MD5").ToLower();
    }
    else
    {
      switch (i)
      {
        case 16: return "000000000000000";
        case 32: return "000000000000000000000000000000";
        default: return "请确保调用函数时第二个参数为16或32";
      }

    }
  }