C#的最實用的的字串加密解密方法大全

來源:互聯網
上載者:User
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 System.Web.UI.HtmlControls;using System.IO;using System.Security.Cryptography;using System.Text;namespace sql_function{    /// <summary>    /// 所有加密方法    /// 定義字串加密介面 [MD5加密,SHA1加密,字串加密]    前台只需定這樣定義:    /// sql_function.InterFaceStringEncryptionDecryption QueryStringEncodeCodeAndDncodeCode =new sql_function.StringEncryptionDecryption();    /// 說明:其中sql_function代表命名空間名稱 InterFaceStringEncryptionDecryption代表介面名稱   StringEncryptionDecryption代表類名    /// </summary>    publicinterfaceInterFaceStringEncryptionDecryption    {        #region (1) QueryString加密與解密 開始        /// <summary>        /// QueryString加密        /// </summary>        /// <param name="StringSQL"></param>        /// <returns></returns>        stringQueryStringEncodeCode(stringStringSQL);                /// <summary>        /// QueryString解密        /// </summary>        /// <param name="StringSQL"></param>        /// <returns></returns>        stringQueryStringDncodeCode(stringStringSQL);        #endregion        #region (2) Rijndael演算法        /// <summary>        /// 加密方法        /// </summary>        /// <param name="Source">待加密的串</param>        /// <returns>經過加密的串</returns>        stringRijndaelEncrypt(stringSource);        /// <summary>        /// 解密方法        /// </summary>        /// <param name="Source">待解密的串</param>        /// <returns>經過解密的串</returns>        stringRijndaelDecrypt(stringSource);        #endregion (2) Rijndael演算法        #region ( 3 ) Base64與UTF8混用        /// <summary>        /// 字串加密        /// </summary>        /// <param name="bb"></param>        /// <returns></returns>        stringBUEncrypt(string bb);        /// <summary>        /// 字串解密        /// </summary>        /// <param name="aa"></param>        /// <returns></returns>        stringBUDecrypt(string aa);        #endregion        #region ( 4 )固定密鑰演算法        /// <summary>        /// 字串加密        /// </summary>        /// <param name="strText"></param>        /// <returns></returns>        stringSKeyEncrypt(string strText);        /// <summary>        /// 字串解密        /// </summary>        /// <param name="strText"></param>        /// <returns></returns>        stringSKeyDecrypt(string strText);        #endregion        #region ( 5 )DES演算法        /// <summary>        /// DES加密        /// </summary>        /// <param name="strSource"></param>        /// <returns></returns>        stringDESEncrypt(string strSource);        /// <summary>        /// DES解密        /// </summary>        /// <param name="strSource"></param>        /// <returns></returns>        stringDESDecrypt(string strSource);        #endregion        #region ( 6 )   加密密碼MD5T和SHA1        /// <summary>        /// 加密密碼MD5T和SHA1        /// </summary>        /// <param name="strSource">字串</param>        /// <param name="strFlag">加密類別</param>        /// <param name="substringlen">加密長度</param>        /// <returns></returns>        string encrypting(string strSource,int strFlag,int substringlen);        #endregion    }        /// <summary>    /// 定義介面類 加密的類的方法    /// </summary>    publicclassStringEncryptionDecryption:InterFaceStringEncryptionDecryption    {        #region (1) QueryString加密與解密 開始        /// <summary>        /// QueryString加密        /// </summary>        /// <param name="code"></param>        /// <returns></returns>        publicstringQueryStringEncodeCode(string code)        {            string result ="";            if(code ==null|| code =="")            {                result ="";            }            else            {                result =Convert.ToBase64String(System.Text.Encoding.Default.GetBytes(""+ code +"")).Replace("+","%2B");            }            return result;        }        /// <summary>        /// QueryString解密        /// </summary>        /// <param name="code"></param>        /// <returns></returns>        publicstringQueryStringDncodeCode(string code)        {            string result ="";            if(code ==null|| code =="")            {                result ="";            }            else            {                try                {                    result =System.Text.Encoding.Default.GetString(Convert.FromBase64String(code.Replace("%2B","+")));                }                catch(FormatException ex)///拋出異常 [錯誤資訊“Base-64字元數組的無效長度”]                {                    result ="0";                }            }            return result;        }        #endregion (1) QueryString加密與解密 結束        #region ( 2 ) Rijndael演算法        privatestaticSymmetricAlgorithm mobjCryptoService =newRijndaelManaged();        privatestaticstringKey="Guz(%&hj7x89H$yuBI0456FtmaT5&fvHUFCy76*h%(HilJ$lhj!y6&(*jkP87jH7";        /// <summary>        /// 獲得密鑰        /// </summary>        /// <returns>密鑰</returns>        privatebyte[]GetLegalKey()        {            string sTemp =Key;            mobjCryptoService.GenerateKey();            byte[] bytTemp = mobjCryptoService.Key;            intKeyLength= bytTemp.Length;            if(sTemp.Length>KeyLength)                sTemp = sTemp.Substring(0,KeyLength);            elseif(sTemp.Length<KeyLength)                sTemp = sTemp.PadRight(KeyLength,' ');            returnASCIIEncoding.ASCII.GetBytes(sTemp);        }        /// <summary>        /// 獲得初始向量IV        /// </summary>        /// <returns>初試向量IV</returns>        privatebyte[]GetLegalIV()        {            string sTemp ="E4ghj*Ghg7!rNIfb&95GUY86GfghUb#er57HBh(u%g6HJ($jhWk7&!hg4ui%$hjk";            mobjCryptoService.GenerateIV();            byte[] bytTemp = mobjCryptoService.IV;            intIVLength= bytTemp.Length;            if(sTemp.Length>IVLength)                sTemp = sTemp.Substring(0,IVLength);            elseif(sTemp.Length<IVLength)                sTemp = sTemp.PadRight(IVLength,' ');            returnASCIIEncoding.ASCII.GetBytes(sTemp);        }        /// <summary>        /// 加密方法        /// </summary>        /// <param name="Source">待加密的串</param>        /// <returns>經過加密的串</returns>        publicstringRijndaelEncrypt(stringSource)        {            byte[] bytIn = UTF8Encoding.UTF8.GetBytes(Source);            MemoryStream ms =newMemoryStream();            mobjCryptoService.Key=GetLegalKey();            mobjCryptoService.IV =GetLegalIV();            ICryptoTransform encrypto = mobjCryptoService.CreateEncryptor();            CryptoStream cs =newCryptoStream(ms, encrypto,CryptoStreamMode.Write);            cs.Write(bytIn,0, bytIn.Length);            cs.FlushFinalBlock();            ms.Close();            byte[] bytOut = ms.ToArray();            returnConvert.ToBase64String(bytOut);        }        /// <summary>        /// 解密方法        /// </summary>        /// <param name="Source">待解密的串</param>        /// <returns>經過解密的串</returns>        publicstringRijndaelDecrypt(stringSource)        {            try            {                byte[] bytIn =Convert.FromBase64String(Source);                MemoryStream ms =newMemoryStream(bytIn,0, bytIn.Length);                mobjCryptoService.Key=GetLegalKey();                mobjCryptoService.IV =GetLegalIV();                ICryptoTransform encrypto = mobjCryptoService.CreateDecryptor();                CryptoStream cs =newCryptoStream(ms, encrypto,CryptoStreamMode.Read);                StreamReader sr =newStreamReader(cs);                return sr.ReadToEnd();            }            catch(Exception ex)            {                return ex.Message;            }        }        #endregion        #region ( 3 )Base64與UTF8混用        //字串加密        publicstringBUEncrypt(string bb)        {            byte[]by=newbyte[bb.Length];            by=System.Text.Encoding.UTF8.GetBytes(bb);            string r =Convert.ToBase64String(by);            return r;        }        //字串解密        publicstringBUDecrypt(string aa)        {            try            {                byte[]by=Convert.FromBase64String(aa);                string r =Encoding.UTF8.GetString(by);                return r;            }            catch(Exception ex)            {                return ex.Message;            }        }        #endregion        #region ( 4 )固定密鑰演算法        publicstaticByte[]Iv64={11,22,33,44,55,66,77,88};        publicstaticByte[] byKey64 ={10,20,30,40,50,60,70,80};        //字串加密        publicstringSKeyEncrypt(string strText)        {            try            {                DESCryptoServiceProvider des =newDESCryptoServiceProvider();                Byte[] inputByteArray =Encoding.UTF8.GetBytes(strText);                MemoryStream ms =newMemoryStream();                CryptoStream cs =newCryptoStream(ms, des.CreateEncryptor(byKey64,Iv64),CryptoStreamMode.Write);                cs.Write(inputByteArray,0, inputByteArray.Length);                cs.FlushFinalBlock();                returnConvert.ToBase64String(ms.ToArray());            }            catch(Exception ex)            {                return ex.Message;            }        }        //字串解密        publicstringSKeyDecrypt(string strText)        {            Byte[] inputByteArray =newbyte[strText.Length];            try            {                DESCryptoServiceProvider des =newDESCryptoServiceProvider();                inputByteArray =Convert.FromBase64String(strText);                MemoryStream ms =newMemoryStream();                CryptoStream cs =newCryptoStream(ms, des.CreateDecryptor(byKey64,Iv64),CryptoStreamMode.Write);                cs.Write(inputByteArray,0, inputByteArray.Length);                cs.FlushFinalBlock();                System.Text.Encoding encoding =System.Text.Encoding.UTF8;                return encoding.GetString(ms.ToArray());            }            catch(Exception ex)            {                return ex.Message;            }        }        #endregion        #region ( 5 )DES演算法        publicstaticbyte[]DESKey=newbyte[]{0x82,0xBC,0xA1,0x6A,0xF5,0x87,0x3B,0xE6,0x59,0x6A,0x32,0x64,0x7F,0x3A,0x2A,0xBB,0x2B,0x68,0xE2,0x5F,0x06,0xFB,0xB8,0x2D,0x67,0xB3,0x55,0x19,0x4E,0xB8,0xBF,0xDD};        /// <summary>        /// DES加密        /// </summary>        /// <param name="strSource">待加密字串</param>        /// <param name="key">32位Key值</param>        /// <returns>加密後的字串</returns>        publicstringDESEncrypt(string strSource)        {            returnDESEncryptF(strSource,DESKey);        }        privatestringDESEncryptF(string strSource,byte[] key)        {            SymmetricAlgorithm sa =Rijndael.Create();            sa.Key= key;            sa.Mode=CipherMode.ECB;            sa.Padding=PaddingMode.Zeros;            MemoryStream ms =newMemoryStream();            CryptoStream cs =newCryptoStream(ms, sa.CreateEncryptor(),CryptoStreamMode.Write);            byte[] byt =Encoding.Unicode.GetBytes(strSource);            cs.Write(byt,0, byt.Length);            cs.FlushFinalBlock();            cs.Close();            returnConvert.ToBase64String(ms.ToArray());        }        /// <summary>        /// DES解密        /// </summary>        /// <param name="strSource">待解密的字串</param>        /// <param name="key">32位Key值</param>        /// <returns>解密後的字串</returns>        publicstringDESDecrypt(string strSource)        {            returnDESDecryptF(strSource,DESKey);        }        privatestringDESDecryptF(string strSource,byte[] key)        {            try            {                SymmetricAlgorithm sa =Rijndael.Create();                sa.Key= key;                sa.Mode=CipherMode.ECB;                sa.Padding=PaddingMode.Zeros;                ICryptoTransform ct = sa.CreateDecryptor();                byte[] byt =Convert.FromBase64String(strSource);                MemoryStream ms =newMemoryStream(byt);                CryptoStream cs =newCryptoStream(ms, ct,CryptoStreamMode.Read);                StreamReader sr =newStreamReader(cs,Encoding.Unicode);                return sr.ReadToEnd();            }            catch(Exception ex)            {                return ex.Message;            }        }        #endregion        #region ( 6 )   加密密碼MD5T和SHA1        /// <summary>        /// 加密密碼MD5T和SHA1        /// </summary>        /// <param name="strSource">字串</param>        /// <param name="strFlag">加密類別</param>        /// <param name="substringlen">加密長度</param>        /// <returns></returns>        ///         publicstring encrypting(string strSource,int strFlag,int substringlen)        {            string ss ="";            if(strFlag ==1)///MD5加密            {                if(substringlen ==16)//16位MD5加密(取32位加密的9~25字元)                {                    ss =FormsAuthentication.HashPasswordForStoringInConfigFile(strSource,"MD5").ToLower().Substring(8,16);                }                elseif(substringlen ==32)//32位加密                {                    ss =FormsAuthentication.HashPasswordForStoringInConfigFile(strSource,"MD5").ToLower();                }            }            elseif(strFlag ==2)///SHA1加密            {                if(substringlen ==16)//SHA1 16位加密                {                    ss =FormsAuthentication.HashPasswordForStoringInConfigFile(strSource,"SHA1").ToLower().Substring(8,16);                }                elseif(substringlen ==32)//SHA1 40位加密                {                    ss =FormsAuthentication.HashPasswordForStoringInConfigFile(strSource,"SHA1").ToLower();                }            }            else            {                ss ="";            }            return ss;        }        #endregion    }}

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.