Chinaunix首页 | 论坛 | 博客
  • 博客访问: 511970
  • 博文数量: 88
  • 博客积分: 2256
  • 博客等级: 大尉
  • 技术积分: 921
  • 用 户 组: 普通用户
  • 注册时间: 2009-12-08 23:20
个人简介

积硅步,行千里

文章分类

全部博文(88)

文章存档

2019年(5)

2018年(1)

2016年(15)

2015年(23)

2013年(3)

2012年(6)

2011年(3)

2010年(22)

2009年(10)

我的朋友

分类: C#/.net

2015-04-29 15:17:41

MD5的加密处理应用还是比较多,由于破解难度很大,基本上大型网站或者软件商,密码加密一般采用这种方式居多。

而MD5可以用来获得32、 16、8等全部部分内容加密内容,也可以获取其加密后的哈希值。

点击(此处)折叠或打开

  1. /// 获得32位的MD5加密
  2.         ///
  3.         ///
  4.         ///
  5.         public static string GetMD5_32(string input)
  6.         {
  7.             System.Security.Cryptography.MD5 md5 = System.Security.Cryptography.MD5.Create();
  8.             byte[] data = md5.ComputeHash(System.Text.Encoding.Default.GetBytes(input));
  9.             StringBuilder sb = new StringBuilder();
  10.             for (int i = 0; i < data.Length; i++)
  11.             {
  12.                 sb.Append(data[i].ToString("x2"));
  13.             }
  14.             return sb.ToString();
  15.         }

  16.         ///
  17.         /// 获得16位的MD5加密
  18.         ///
  19.         ///
  20.         ///
  21.         public static string GetMD5_16(string input)
  22.         {
  23.             return GetMD5_32(input).Substring(8, 16);
  24.         }
  25.         ///
  26.         /// 获得8位的MD5加密
  27.         ///
  28.         ///
  29.         ///
  30.         public static string GetMD5_8(string input)
  31.         {
  32.             return GetMD5_32(input).Substring(8, 8);
  33.         }
  34.         ///
  35.         /// 获得4位的MD5加密
  36.         ///
  37.         ///
  38.         ///
  39.         public static string GetMD5_4(string input)
  40.         {
  41.             return GetMD5_32(input).Substring(8, 4);
  42.         }

  43.         public static string MD5EncryptHash(String input)
  44.         {
  45.             MD5 md5 = new MD5CryptoServiceProvider();
  46.             //the GetBytes method returns byte array equavalent of a string
  47.             byte[] res = md5.ComputeHash(Encoding.Default.GetBytes(input), 0, input.Length);
  48.             char[] temp = new char[res.Length];
  49.             //copy to a char array which can be passed to a String constructor
  50.             Array.Copy(res, temp, res.Length);
  51.             //return the result as a string
  52.             return new String(temp);
  53.         }

对文件添加MD5标签及验证
这种方式比较有趣,我也是最近才发现其中的奥妙,其实我们为了防止文件被修改,可以采用这种方式预先添加MD5码,然后在程序代码中进行验证,这样至少可以减少部分篡改的行为吧,因为只要文件有些少的修改,Md5码将会发生变化的,呵呵。

点击(此处)折叠或打开

  1. ///
  2.         /// 对给定文件路径的文件加上标签
  3.         ///
  4.         /// 要加密的文件的路径
  5.         /// 标签的值
  6.         public static bool AddMD5(string path)
  7.         {
  8.             bool IsNeed = true;

  9.             if (CheckMD5(path)) //已进行MD5处理
  10.                 IsNeed = false;

  11.             try
  12.             {
  13.                 FileStream fsread = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read);
  14.                 byte[] md5File = new byte[fsread.Length];
  15.                 fsread.Read(md5File, 0, (int)fsread.Length); // 将文件流读取到Buffer中
  16.                 fsread.Close();

  17.                 if (IsNeed)
  18.                 {
  19.                     string result = MD5Buffer(md5File, 0, md5File.Length); // 对Buffer中的字节内容算MD5
  20.                     byte[] md5 = System.Text.Encoding.ASCII.GetBytes(result); // 将字符串转换成字节数组以便写人到文件中
  21.                     FileStream fsWrite = new FileStream(path, FileMode.Open, FileAccess.ReadWrite);
  22.                     fsWrite.Write(md5File, 0, md5File.Length); // 将文件,MD5值 重新写入到文件中。
  23.                     fsWrite.Write(md5, 0, md5.Length);
  24.                     fsWrite.Close();
  25.                 }
  26.                 else
  27.                 {
  28.                     FileStream fsWrite = new FileStream(path, FileMode.Open, FileAccess.ReadWrite);
  29.                     fsWrite.Write(md5File, 0, md5File.Length);
  30.                     fsWrite.Close();
  31.                 }
  32.             }
  33.             catch
  34.             {
  35.                 return false;
  36.             }

  37.             return true;
  38.         }

  39.         ///
  40.         /// 对给定路径的文件进行验证
  41.         ///
  42.         ///
  43.         /// 是否加了标签或是否标签值与内容值一致
  44.         public static bool CheckMD5(string path)
  45.         {
  46.             try
  47.             {
  48.                 FileStream get_file = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read);
  49.                 byte[] md5File = new byte[get_file.Length]; // 读入文件
  50.                 get_file.Read(md5File, 0, (int)get_file.Length);
  51.                 get_file.Close();

  52.                 string result = MD5Buffer(md5File, 0, md5File.Length - 32); // 对文件除最后32位以外的字节计算MD5,这个32是因为标签位为32位。
  53.                 string md5 = System.Text.Encoding.ASCII.GetString(md5File, md5File.Length - 32, 32); //读取文件最后32位,其中保存的就是MD5值
  54.                 return result == md5;
  55.             }
  56.             catch
  57.             {
  58.                 return false;
  59.             }
  60.         }

  61.         ///
  62.         /// 计算文件的MD5值
  63.         ///
  64.         /// MD5签名文件字符数组
  65.         /// 计算起始位置
  66.         /// 计算终止位置
  67.         /// 计算结果
  68.         private static string MD5Buffer(byte[] MD5File, int index, int count)
  69.         {
  70.             System.Security.Cryptography.MD5CryptoServiceProvider get_md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
  71.             byte[] hash_byte = get_md5.ComputeHash(MD5File, index, count);
  72.             string result = System.BitConverter.ToString(hash_byte);

  73.             result = result.Replace("-", "");
  74.             return result;
  75.         }
  76.         #endregion
SHA256加密算法

点击(此处)折叠或打开

  1. /// SHA256函数
  2.         ///
  3.         /// 原始字符串
  4.         /// SHA256结果(返回长度为44字节的字符串)
  5.         public static string SHA256(string str)
  6.         {
  7.             byte[] SHA256Data = Encoding.UTF8.GetBytes(str);
  8.             SHA256Managed Sha256 = new SHA256Managed();
  9.             byte[] Result = Sha256.ComputeHash(SHA256Data);
  10.             return Convert.ToBase64String(Result); //返回长度为44字节的字符串
  11.         }
以下是应用在开发中的实例:
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Configuration;
  4. using System.Data;
  5. using System.Data.SqlClient;
  6. using System.Linq;
  7. using System.Security.Cryptography;
  8. using System.Text;

  9. namespace MIS
  10. {
  11.     class Encrypt
  12.     {

  13.         //数据存入,直接将byte[]保存入binary字段
  14.         public static int AccountRegister(string accountName, string password,string firstname,string position,string phone)
  15.         {
  16.             //string connstr = ConfigurationManager.ConnectionStrings["connstr"].ConnectionString;
  17.             string connstr = configxml.xmlconn.readxml();
  18.             SqlConnection conn = new SqlConnection(connstr);
  19.             string bytePassword = Encrypt.GetMD5_32(password);//使用32位MD5加密
  20.             conn.Open();

  21.             SqlCommand cmd = new SqlCommand("Account_Add", conn);
  22.             cmd.CommandType = CommandType.StoredProcedure;
  23.             SqlParameter prmAccountName = cmd.Parameters.Add(new SqlParameter("@accountName", SqlDbType.NVarChar, 50));
  24.             prmAccountName.Value = accountName;
  25.             SqlParameter prmPassword = cmd.Parameters.Add(new SqlParameter("@password", SqlDbType.NVarChar, 50));
  26.             prmPassword.Value = bytePassword;
  27.             SqlParameter prmFirstName = cmd.Parameters.Add(new SqlParameter("@FirstName", SqlDbType.NVarChar, 50));
  28.             prmFirstName.Value = firstname;
  29.             SqlParameter prmPosition = cmd.Parameters.Add(new SqlParameter("@position", SqlDbType.NVarChar, 50));
  30.             prmPosition.Value = position;
  31.             SqlParameter prmPhone = cmd.Parameters.Add(new SqlParameter("@phone", SqlDbType.NVarChar, 50));
  32.             prmPhone.Value = phone;
  33.             int myInt = cmd.ExecuteNonQuery();
  34.             cmd.Dispose();
  35.             conn.Close();
  36.             return myInt;
  37.         }
  38.         //更新账户信息
  39.         public static int AccountUpdate(string accountName, string password)
  40.         {
  41.             string connstr = ConfigurationManager.ConnectionStrings["connstr"].ConnectionString;
  42.             string bytePassword = Encrypt.GetMD5_32(password);
  43.             SqlConnection conn = new SqlConnection(connstr);
  44.             conn.Open();
  45.             SqlCommand cmd = new SqlCommand("Account_Update", conn);
  46.             cmd.CommandType = CommandType.StoredProcedure;
  47.             SqlParameter prmAccountName = cmd.Parameters.Add(new SqlParameter("@accountName", SqlDbType.NVarChar, 50));
  48.             prmAccountName.Value = accountName;
  49.             SqlParameter prmPassword = cmd.Parameters.Add(new SqlParameter("@password", SqlDbType.NVarChar, 50));
  50.             prmPassword.Value = bytePassword;
  51.             int myInt = cmd.ExecuteNonQuery();
  52.             cmd.Dispose();
  53.             conn.Close();
  54.             return myInt;
  55.         }
  56.         /// SHA256函数
  57.         ///
  58.         /// 原始字符串
  59.         /// SHA256结果(返回长度为44字节的字符串)
  60.         ///
  61.         //哈系散列转换
  62.         public static byte[] GetSaltedPassword(string password)
  63.         {
  64.             SHA1 sha1 = SHA1.Create();
  65.             //应用System.Text空间下的Unicode.GetBytes方法获得byte.
  66.             byte[] bytePassword = sha1.ComputeHash(Encoding.Unicode.GetBytes(password));
  67.             return bytePassword;
  68.         }
  69.         public static string SHA256(string str)
  70.         {
  71.             byte[] SHA256Data = Encoding.UTF8.GetBytes(str);
  72.             SHA256Managed Sha256 = new SHA256Managed();
  73.             byte[] Result = Sha256.ComputeHash(SHA256Data);
  74.             return Convert.ToBase64String(Result); //返回长度为44字节的字符串
  75.         }
  76.         /// 获得32位的MD5加密
  77.         ///
  78.         ///
  79.         ///
  80.         public static string GetMD5_32(string input)
  81.         {
  82.             System.Security.Cryptography.MD5 md5 = System.Security.Cryptography.MD5.Create();
  83.             byte[] data = md5.ComputeHash(System.Text.Encoding.Default.GetBytes(input));
  84.             StringBuilder sb = new StringBuilder();
  85.             for (int i = 0; i < data.Length; i++)
  86.             {
  87.                 sb.Append(data[i].ToString("x2"));
  88.             }
  89.             return sb.ToString();
  90.         }
  91.         ///
  92.         /// 获得16位的MD5加密
  93.         ///
  94.         ///
  95.         ///
  96.         public static string GetMD5_16(string input)
  97.         {
  98.             return GetMD5_32(input).Substring(8, 16);
  99.         }
  100.         ///
  101.         /// 获得8位的MD5加密
  102.         ///
  103.         ///
  104.         ///
  105.         public static string GetMD5_8(string input)
  106.         {
  107.             return GetMD5_32(input).Substring(8, 8);
  108.         }
  109.         ///
  110.         /// 获得4位的MD5加密
  111.         ///
  112.         ///
  113.         ///
  114.         public static string GetMD5_4(string input)
  115.         {
  116.             return GetMD5_32(input).Substring(8, 4);
  117.         }

  118.         public static string MD5EncryptHash(String input)
  119.         {
  120.             MD5 md5 = new MD5CryptoServiceProvider();
  121.             //the GetBytes method returns byte array equavalent of a string
  122.             byte[] res = md5.ComputeHash(Encoding.Default.GetBytes(input), 0, input.Length);
  123.             char[] temp = new char[res.Length];
  124.             //copy to a char array which can be passed to a String constructor
  125.             Array.Copy(res, temp, res.Length);
  126.             //return the result as a string
  127.             return new String(temp);
  128.         }
  129.     }
  130. }


阅读(4061) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~