C#與加密

1.C#的MD5登陸驗證

            try
            {
                conn.Open();
                if (conn.State.ToString() == "Open")
                {
                }
                else
                {
                    MessageBox.Show("連接數據庫未成功", "提示");
                    return;
                }
                OracleCommand cmd = conn.CreateCommand();

                cmd.CommandText = "select * from PL_USER where CNAME = '" + this.textBoxUsrName.Text.ToString() + "'";//在這兒寫sql語句 

                OracleDataReader odr_psw = cmd.ExecuteReader();//創建一個OracleDateReader對象

                System.Security.Cryptography.MD5CryptoServiceProvider md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
                byte[] bs = System.Text.Encoding.UTF8.GetBytes(this.textBoxPassWord.Text.ToString());
                bs = md5.ComputeHash(bs);
                System.Text.StringBuilder s = new System.Text.StringBuilder();
                foreach (byte b in bs)
                {
                    s.Append(b.ToString("x2").ToUpper());
                }
                String password = s.ToString();
                String Oraclepsw=null;
                if (odr_psw.Read())
                {
                    Oraclepsw = odr_psw["CPWD"].ToString();
                }
                if (password.Equals(Oraclepsw))
                {
                    XmlDocument xmlDoc = new XmlDocument();
                    xmlDoc.Load(@System.IO.Directory.GetCurrentDirectory() + "\\LoginUsr.xml");
                    XmlNode nodeusr = xmlDoc.SelectSingleNode("//LogUsr/Usr");
                    nodeusr.Attributes["name"].Value = this.textBoxUsrName.Text.ToString();
                    xmlDoc.Save(@System.IO.Directory.GetCurrentDirectory() + "\\LoginUsr.xml");
                    Splasher.iCloseFlag = 1;
                }
                else {
                    MessageBox.Show("用戶名或密碼錯誤!");
                }
            }
            catch (Exception ee)
            {
                MessageBox.Show(ee.Message);
            }
            finally {
                conn.Close();
            }
            Splasher.iCloseFlag = 1;


2.C#產生哈希摘要,控制文件不被外部修改

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Web;
using System.Configuration;
using System.Security.Cryptography;
using System.Reflection;

namespace HashCheck
{
    class HashFileCheck
    {
        public string MD5File(string fileName)
        {
            return HashFile(fileName, "md5");
        }

        /// <summary>
        /// 計算文件的哈希值
        /// </summary>
        /// <param name="fileName">要計算哈希值的文件名和路徑</param>
        /// <param name="algName">算法:sha1,md5</param>
        /// <returns>哈希值16進制字符串</returns>
        private string HashFile(string fileName, string algName)
        {
            if (!System.IO.File.Exists(fileName))
                return string.Empty;

            FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
            byte[] hashBytes = HashData(fs, algName);
            fs.Close();
            return ByteArrayToHexString(hashBytes);
        }

        /// <summary>
        /// 計算哈希值
        /// </summary>
        /// <param name="stream">要計算哈希值的 Stream</param>
        /// <param name="algName">算法:sha1,md5</param>
        /// <returns>哈希值字節數組</returns>
        private byte[] HashData(Stream stream, string algName)
        {
            HashAlgorithm algorithm;
            if (algName == null)
            {
                throw new ArgumentNullException("algName 不能爲 null");
            }
            if (string.Compare(algName, "sha1", true) == 0)
            {
                algorithm = SHA1.Create();
            }
            else
            {
                if (string.Compare(algName, "md5", true) != 0)
                {
                    throw new Exception("algName 只能使用 sha1 或 md5");
                }
                algorithm = MD5.Create();
            }
            return algorithm.ComputeHash(stream);
        }
        /// <summary>
        /// 字節數組轉換爲16進製表示的字符串
        /// </summary>
        private string ByteArrayToHexString(byte[] buf)
        {
            int iLen = 0;

            // 通過反射獲取 MachineKeySection 中的 ByteArrayToHexString 方法,該方法用於將字節數組轉換爲16進製表示的字符串。
            Type type = typeof(System.Web.Configuration.MachineKeySection);
            MethodInfo byteArrayToHexString = type.GetMethod("ByteArrayToHexString", BindingFlags.Static | BindingFlags.NonPublic);

            // 字節數組轉換爲16進製表示的字符串
            return (string)byteArrayToHexString.Invoke(null, new object[] { buf, iLen });
        }
    }
}



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