MD5加密驗證字符操作輔助類MD5Util

實現效果

  1. 本輔助類主要是用來方便實現MD5各種長度加密字符、驗證MD5等操作。
  2. MD5即Message-Digest Algorithm 5(信息-摘要算法 5),用於確保信息傳輸完整一致。是計算機廣泛使用的散列算法之一。
  3. MD5已經廣泛使用在爲文件傳輸提供一定的可靠性方面。例如,服務器預先提供一個MD5校驗和,用戶下載完文件以後,用MD5算法計算下載文件的MD5校驗和,然後通過檢查這兩個校驗和是否一致,就能判斷下載的文件是否出錯。

實現步驟

在代碼引用相關的代碼實現動態調用。

實現代碼

  1. 輔助類提供的方法接口如下所示:
/// 獲得32位的MD5加密
public static string GetMD5_32(string input)
/// 獲得16位的MD5加密
public static string GetMD5_16(string input)
/// 獲得8位的MD5加密
public static string GetMD5_8(string input)
/// 獲得4位的MD5加密
public static string GetMD5_4(string input)
/// 添加MD5的前綴,便於檢查有無篡改
public static string AddMD5Profix(string input)
/// 移除MD5的前綴
public static string RemoveMD5Profix(string input)
/// 驗證MD5前綴處理的字符串有無被篡改
public static bool ValidateValue(string input)
/// 對給定文件路徑的文件加上標籤
public static bool AddMD5(string path)
/// 對給定路徑的文件進行驗證,如果一致返回True,否則返回False
public static bool CheckMD5(string path)
  1. 輔助類MD5Util的使用例子代碼如下所示:
//爲文件增加MD5編碼標籤,然後驗證是否被修改
string file = @"d:  estmd5.xls";
bool flag1 = MD5Util.AddMD5(file);
Console.WriteLine(flag1);
//對給定路徑的文件進行驗證,如果一致返回True,否則返回False
bool flag2 = MD5Util.CheckMD5(file);
Console.WriteLine(flag2);

附上源碼

    /// <summary>
    /// MD5各種長度加密字符、驗證MD5等操作輔助類
    /// </summary>
    public class MD5Util
    {
        /// <summary>
        /// 構造函數
        /// </summary>
        public MD5Util()
        {
        }

        /// <summary>
        /// 獲得32位的MD5加密
        /// </summary>
        public static string GetMD5_32(string input)
        {
            System.Security.Cryptography.MD5 md5 = System.Security.Cryptography.MD5.Create();
            byte[] data = md5.ComputeHash(System.Text.Encoding.Default.GetBytes(input));
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < data.Length; i++)
            {
                sb.Append(data[i].ToString("x2"));
            }
            return sb.ToString();
        }

        /// <summary>
        /// 獲得16位的MD5加密
        /// </summary>
        public static string GetMD5_16(string input)
        {
            return GetMD5_32(input).Substring(8, 16);
        }

        /// <summary>
        /// 獲得8位的MD5加密
        /// </summary>
        public static string GetMD5_8(string input)
        {
            return GetMD5_32(input).Substring(8, 8);
        }

        /// <summary>
        /// 獲得4位的MD5加密
        /// </summary>
        public static string GetMD5_4(string input)
        {
            return GetMD5_32(input).Substring(8, 4);
        }

        /// <summary>
        /// 添加MD5的前綴,便於檢查有無篡改
        /// </summary>
        public static string AddMD5Profix(string input)
        {
            return GetMD5_4(input) + input;
        }

        /// <summary>
        /// 移除MD5的前綴
        /// </summary>
        public static string RemoveMD5Profix(string input)
        {
            return input.Substring(4);
        }

        /// <summary>
        /// 驗證MD5前綴處理的字符串有無被篡改
        /// </summary>
        public static bool ValidateValue(string input)
        {
            bool res = false;
            if (input.Length >= 4)
            {
                string tmp = input.Substring(4);
                if (input.Substring(0, 4) == GetMD5_4(tmp))
                {
                    res = true;
                }
            }
            return res;
        }

        #region MD5簽名驗證

        /// <summary>
        /// 對給定文件路徑的文件加上標籤
        /// </summary>
        /// <param name="path">要加密的文件的路徑</param>
        /// <returns>標籤的值</returns>
        public static bool AddMD5(string path)
        {
            bool IsNeed = true;

            if (CheckMD5(path)) //已進行MD5處理
                IsNeed = false;

            try
            {
                FileStream fsread = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read);
                byte[] md5File = new byte[fsread.Length];
                fsread.Read(md5File, 0, (int)fsread.Length);                               // 將文件流讀取到Buffer中
                fsread.Close();

                if (IsNeed)
                {
                    string result = MD5Buffer(md5File, 0, md5File.Length);             // 對Buffer中的字節內容算MD5
                    byte[] md5 = System.Text.Encoding.ASCII.GetBytes(result);       // 將字符串轉換成字節數組以便寫人到文件中
                    FileStream fsWrite = new FileStream(path, FileMode.Open, FileAccess.ReadWrite);
                    fsWrite.Write(md5File, 0, md5File.Length);                               // 將文件,MD5值 重新寫入到文件中。
                    fsWrite.Write(md5, 0, md5.Length);
                    fsWrite.Close();
                }
                else
                {
                    FileStream fsWrite = new FileStream(path, FileMode.Open, FileAccess.ReadWrite);
                    fsWrite.Write(md5File, 0, md5File.Length);
                    fsWrite.Close();
                }
            }
            catch
            {
                return false;
            }

            return true;
        }

        /// <summary>
        /// 對給定路徑的文件進行驗證,如果一致返回True,否則返回False
        /// </summary>
        /// <param name="path"></param>
        /// <returns>是否加了標籤或是否標籤值與內容值一致</returns>
        public static bool CheckMD5(string path)
        {
            try
            {
                FileStream get_file = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read);
                byte[] md5File = new byte[get_file.Length];                                      // 讀入文件
                get_file.Read(md5File, 0, (int)get_file.Length);
                get_file.Close();

                string result = MD5Buffer(md5File, 0, md5File.Length - 32);             // 對文件除最後32位以外的字節計算MD5,這個32是因爲標籤位爲32位。
                string md5 = System.Text.Encoding.ASCII.GetString(md5File, md5File.Length - 32, 32);   //讀取文件最後32位,其中保存的就是MD5值
                return result == md5;
            }
            catch
            {
                return false;
            }
        }

        /// <summary>
        /// 計算文件的MD5值
        /// </summary>
        /// <param name="MD5File">MD5簽名文件字符數組</param>
        /// <param name="index">計算起始位置</param>
        /// <param name="count">計算終止位置</param>
        /// <returns>計算結果</returns>
        private static string MD5Buffer(byte[] MD5File, int index, int count)
        {
            System.Security.Cryptography.MD5CryptoServiceProvider get_md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
            byte[] hash_byte = get_md5.ComputeHash(MD5File, index, count);
            string result = System.BitConverter.ToString(hash_byte);

            result = result.Replace("-", "");
            return result;
        } 
        #endregion

        private void Test()
        {
            string o = "i love u";
            o = AddMD5Profix(o);
            //o += " ";
            Console.WriteLine(o);
            Console.WriteLine(ValidateValue(o));

            o = RemoveMD5Profix(o);
            Console.WriteLine(o);

        }
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章