C#几种实现MD5加密

C#常用加密解密方法(MD5加密解密) 本节主要分享MD5加密解密:MD5全称是message-digest algorithm 5,简单的说就是单向的加密,也就是说无法根据密文推导出明文。1、对一段信息生成信息摘要,该摘要对该信息具有唯一性,可以作为数字签名2、用于验证文件的有效性(是否有丢失或损坏的数据)3、对用户密码的加密4、在哈希函数中计算散列值。 阅读详情


首先,介绍一下Md5.

MD5的全称是message-digest algorithm 5(信息-摘要算法,在90年代初由mit laboratory for computer science和rsa data security inc的ronald l. rivest开发出来, 经md2、md3和md4发展而来。
MD5具有很好的安全性(因为它具有不可逆的特征,加过密的密文经过解密后和加密前的东东相同的可能性极

引用
using System.Security.Cryptography;
using System.Text;

具体代码如下(写在按钮的Click事件里):
byte[] result = Encoding.Default.GetBytes(this.tbPass.Text.Trim());    //tbPass为输入密码的文本框
MD5 md5 = new MD5CryptoServiceProvider();
byte[] output = md5.ComputeHash(result);
this.tbMd5pass.Text = BitConverter.ToString(output).Replace("-","");  //tbMd5pass为输出加密文本的文本框


                                     方法二

C# md5加密(上)
string a; //加密前数据
string b; //加密后数据
b=System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(a,"MD5")

using   System;
using   System.Security.Cryptography;


方法2

public   static   string   GetMD5(string   myString)  
{
MD5   md5     =   new   MD5CryptoServiceProvider();
byte[]   fromData   =   System.Text.Encoding.Unicode.GetBytes(myString);
byte[]   targetData   =   md5.ComputeHash(fromData);
string   byte2String   =   null;

for   (int   i=0;   i<targetData.Length;   i++)  
{
byte2String   +=   targetData[i].ToString("x");
}

return   byte2String;
}

using   System.Security.Cryptography;


///   <summary>
///   给一个字符串进行MD5加密
///   </summary>
///   <param   name="strText">待加密字符串</param>
///   <returns>加密后的字符串</returns>
public   static   string   MD5Encrypt(string   strText)
{  
MD5   md5   =   new   MD5CryptoServiceProvider();
byte[]   result   =   md5.ComputeHash(System.Text.Encoding.Default.GetBytes(strText));
return   System.Text.Encoding.Default.GetString(result);
}


C# MD5加密
using System.Security.Cryptography;


private void btnOK_Click(object sender, System.EventArgs e)
{
   string strConn = "server=192.168.0.51;database=chengheng;User id=sa; password=123";
   if(texName.Text.Trim()=="")
   {
    this.RegisterStartupScript("sf","<script language='javascript'>alert('用户名不能为空'); document.all('texName').focus()</script>");
    return;
   }
   else if(texPassword.Text.Trim()=="")
   {
    this.RegisterStartupScript("sfs","<script language='javascript'>alert('密码不能为空'); document.all('texPassword').focus()</script>");
    return;
   }
   else
   {
    //将获取的密码加密与数据库中加了密的密码相比较
    byte[] by = md5.ComputeHash(utf.GetBytes(texPassword.Text.Trim()));
    string resultPass = System.Text.UTF8Encoding.Unicode.GetString(by);
    conn.ConnectionString=strConn;
    SqlCommand comm = new SqlCommand();
    string name = texName.Text.Trim().ToString();
    comm.CommandText="select Ruser_pwd,Ruser_nm from Ruser where Accountno = @name";
    comm.Parameters.Add("@name",SqlDbType.NVarChar,40);
    comm.Parameters["@name"].Value=name;
    try
    {    
     conn.Open();
     comm.Connection=conn;
     SqlDataReader dr=comm.ExecuteReader();
     if(dr.Read())
     {
      //用户存在,对密码进行检查
      if(dr.GetValue(0).Equals(resultPass))
      {
       string user_name=dr.GetValue(1).ToString();
       string user_Accountno=texName.Text.Trim();
       Session["logon_name"]=user_name;
       Session["logon_Accountno"]=user_Accountno;
       //登录成功,进行页面导向

      }
      else
      {
       this.RegisterStartupScript("wp","<script language='javascript'>alert('密码错误,请检查。')</script>");
      }
      
     }
     else
     {
      this.RegisterStartupScript("nu","<script language=javascript>alert('用户名不存在,请检查。')</script>");
     }
    }
    catch(Exception exec)
    {
     this.RegisterStartupScript("wc","<script language=javascript>alert('网络连接有异,请稍后重试。')</script>");
    }
    finally
    {
     conn.Close();
    }
   }
}


                                      方法三
C# MD5加密

C#开发笔记   一、C# MD5-16位加密实例,32位加密实例(两种方法)

环境:vs.net2005/sql server2000/xp测试通过
1.MD5 16位加密实例
using System;
using System.Collections.Generic;
using System.Text;
using System.Security.Cryptography;

namespace md5
{
    class Program
    {
        static void Main(string[] args)
        {
             Console.WriteLine(UserMd5("8"));
             Console.WriteLine(GetMd5Str("8"));
         }
        /**//// <summary>
        /// MD5 16位加密 加密后密码为大写
        /// </summary>
        /// <param name="ConvertString"></param>
        /// <returns></returns>
        public static string GetMd5Str(string ConvertString)
        {
             MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
            string t2 = BitConverter.ToString(md5.ComputeHash(UTF8Encoding.Default.GetBytes(ConvertString)), 4, 8);
             t2 = t2.Replace("-", "");
            return t2;
         }

  /**//// <summary>
        /// MD5 16位加密 加密后密码为小写
        /// </summary>
        /// <param name="ConvertString"></param>
        /// <returns></returns>
        public static string GetMd5Str(string ConvertString)
        {
             MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
            string t2 = BitConverter.ToString(md5.ComputeHash(UTF8Encoding.Default.GetBytes(ConvertString)), 4, 8);
             t2 = t2.Replace("-", "");

            t2 = t2.ToLower();

             return t2;
         }


        /**//// <summary>
        /// MD5 32位加密
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
       static  string UserMd5(string str)
        {
            string cl = str;
            string pwd = "";
             MD5 md5 = MD5.Create();//实例化一个md5对像
            // 加密后是一个字节类型的数组,这里要注意编码UTF8/Unicode等的选择 
            byte[] s = md5.ComputeHash(Encoding.UTF8.GetBytes(cl));
            // 通过使用循环,将字节类型的数组转换为字符串,此字符串是常规字符格式化所得
            for (int i = 0; i < s.Length; i++)
            {
                // 将得到的字符串使用十六进制类型格式。格式后的字符是小写的字母,如果使用大写(X)则格式后的字符是大写字符

                 pwd = pwd + s[i].ToString("X");
                
             }
            return pwd;
         }
     }
}

using System.Security.Cryptography;
using System.Text;

public static string StringToMD5Hash(string inputString)
        {
            MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
            byte[] encryptedBytes = md5.ComputeHash(Encoding.ASCII.GetBytes(inputString));
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < encryptedBytes.Length; i++)
            {
                sb.AppendFormat("{0:x2}", encryptedBytes[i]);
            }
            return sb.ToString();
        }


二、首先在界面中引入: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";
            }

        }
    }
C#实现MD5加密                                         方法一首先,先简单介绍一下MD5MD5的全称是message-digest algorithm 5(信息-摘要算法,在90年代初由mit laboratory for computer science和rsa data security inc的ronald l. rivest开发出来, 经md2、md3和md 阅读详情

相关推荐

C#使用MD5算法对密码进行加密

使用 MD5.Create() 方法来创建 MD5 对象更加简洁易读。这种方法也适用于其他过时的加密类,如 SHA1CryptoServiceProvider、SHA256CryptoServiceProvider 等。通过使用基类的 Create() 方法,代码将更加简洁、易读且符合最佳实践。“消息-摘要算法”实际上就是一个单项散列函数,数据块经过单向散列函数得到一个固定长度的散列值,数据块的签名就是计算数据块的散列值,MD5算法的散列值为128位。计算指定字节数组的哈希值。

wenchm的博客 3839

C#常用的加密算法之一 MD5

C#常用的加密算法之一 MD5 参考文章 MD5加密概述,原理及实现 C#常用的加密算法:MD5、Base64、SHA1、SHA256、HmacSHA256、DES、AES、RSA MD5概述 MD5消息摘要算法,属Hash算法一类。MD5算法对输入任意长度的消息进行运行,产生一个128位的消息摘要(32位的数字字母混合码)。 MD5特点 不可逆,相同数据的MD5值肯定一样,不同数据的MD5值不一样 一个MD5理论上的确是可能对应无数多个原文的,因为MD5是有限多个的而原文可以是无数多个。比如主流使用

XHeineken的博客 7387

C#MD5加密技术的实现与应用

本文还有配套的精品资源,点击获取 简介:MD5是一种广泛使用的哈希函数,可以将任意长度的数据转换为固定长度的128位哈希值。在C#中,通过System.Security.Cryptography命名空间中的MD5类,开发者可以实现MD5加密算法,适用于密码存储、数据完整性校验和文件校验等场景。示例代码展示了如何使用C#进行MD5加密,并强调了MD5的快速性和不可逆性。然而,...

weixin_33072399的博客 2717

C# 通用方法MD5计算

基于c#MD5加密算法

qq_41894426的博客 4997

C# MD5加密

public static string MD5(string encypStr) { return MD5(encypStr, "utf-8"); } /** 获取大写的MD5签名结果 */ public static string MD5(string encypStr, string charset) ...

weixin_30824277的博客 134

C#几种加密算法,包括MD5

C#几种加密算法,包括MD5 MD5算法:usingSystem;usingSystem.Text;namespaceBaseStationPDA{////<summary>///SummarydescriptionforMD5.///</summary>publ...

weixin_30682127的博客 124

MD5

此文为复合型文章:引用+原创 ----------- 1.C# MD5 与 java MD5 生成的字符串不一致问题 C# 源码   查了下C#的api ,System.Text.UnicodeEncoding.Unicode.GetBytes(s)用的是utf-16 little-endian编码方式。   java 源码   public static Strin...

cherry cheng的CSDN博客 130

C#加密解密总结

ASCIIEncoding.ASCII.GetBytes(sKey); 这里的sKey必须是8位英文字母。 //须添加对System.Web的引用 using System.Web.Security;   ...   /// &lt;summary&gt; /// SHA1加密字符串 /// &lt;/summary&gt; /// &lt;param name="sou...

weixin_34015336的博客 161

Base64、Md5、Des加密

using System;using System.Data;using System.Configuration;using System.Web;using System.Web.Security;using System.Web.UI;using System.Web.UI.WebControls;using System.Web.UI.WebControls.WebParts;using ...

weixin_30567471的博客 73

常用MD5,UNICODE,SHA1加密

【代码】常用MD5,UNICODE,SHA1加密类。

weisico.com的博客 251

C#中使用MD5对用户密码加密与解密

C#中常涉及到对用户密码的加密于解密的算法,其中使用MD5加密是最常见的的实现方式。本文总结了通用的算法并结合了自己的一点小经验,分享给大家。 一.使用16位、32位、64位MD5方法对用户名加密 1)16位的MD5加密 /// <summary> /// 16位MD5加密 /// </summary> /// <param name="password"></param> /// <returns></returns> .

u011555996的博客 1万+

C#中使用MD5加密的方法

文章介绍了五种使用MD5的方法,提供一种思路和参考,实例1是一种较安全的方法。如果不支持中文,可将中文编码取出进行MD5加密。本文中的所有方法均来自网络,感谢各位作者提供。

wonsoft的专栏 11万+

C#用使用MD5

原理: MD5文件打开关闭没事,改变内容MD5码就会改变,是对内容进行加密后的结果。 MD5 (tanajiya.tar.gz) = 38b8c2c1093dd0fec383a9d9ac940515,这就是tanajiya.tar.gz文件的数字签名。MD5将整个文件当作一个大文本信息,通过其不可逆的字符串变换算法,产生了这个唯一的MD5信息摘要。 大家都知...

漓涂 5235

C# —— MD5编码

MD5:属于一种加密算法,单向不可逆加密。1 对用户密码或者一些隐私的信息进行加密处理2 对一段文字生产成信息摘要,这个摘要是具有唯一性的,可以作为数字的签名。3 用于验证文件的有效性4 在哈希函数计算散列值。

一个新人博客,愿多多支持。 1426

C#MD5加密

MD5加密算法:单向不可逆加密MD5主要用途:1、对一段信息生成信息摘要,该摘要对该信息具有唯一性,可以作为数字签名。2、用于验证文件的有效性(是否有丢失或损坏的数据),3、对用户密码的加密,4、在哈希函数中计算散列值从上边的主要用途中我们看到,由于算法的某些不可逆特征,在加密应用上有较好的安全性。通过使用MD5加密算法,我们输入一个任意长度的字节串,都会生成一个128位的整数。所以根据这一点M...

ChaITSimpleLove的博客 3648
上一篇: jqGrid asp.net mvc 使用
下一篇: 尽可能地使用强类型数据
asdwww007
博客等级 码龄16年 5粉丝 13原创
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值