DESCryptoServiceProvider加密、解密


.net名稱空間System.Security.Cryptography下DESCryptoServiceProvider類為我們提供了加密和解密方法,我們只需少許代碼便可實現加密和解密。

稍感不托的地方,如果不是自行加密的在解密時會報錯。

使用注意事項,密鑰64位,8個字符。

定義默認加密密鑰

const string KEY_64 = "ChinabCd";
const string IV_64 = "ChinabCd";

加密

/// <summary>
/// 按指定鍵值進行加密
/// </summary>
/// <param name="strContent">要加密字符</param>
/// <param name="strKey">自定義鍵值</param>
/// <returns></returns>

public static string EnCrypt(string strContent, string strKey)

        {
            if (string.IsNullOrEmpty(strContent)) return string.Empty;
            if (strKey.Length > 8) strKey = strKey.Substring(0, 8); else strKey = KEY_64;
            byte[] byKey = System.Text.ASCIIEncoding.ASCII.GetBytes(strKey);
            byte[] byIV = System.Text.ASCIIEncoding.ASCII.GetBytes(IV_64);

            DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider();
            int i = cryptoProvider.KeySize;
            MemoryStream ms = new MemoryStream();
            CryptoStream cst = new CryptoStream(ms, cryptoProvider.CreateEncryptor(byKey, byIV), CryptoStreamMode.Write);

            StreamWriter sw = new StreamWriter(cst);
            sw.Write(strContent);
            sw.Flush();
            cst.FlushFinalBlock();
            sw.Flush();
            return Convert.ToBase64String(ms.GetBuffer(), 0, (int)ms.Length);
        }
View Code

 解密

 /// <summary>
        /// 按指定鍵值進行解密
        /// </summary>
        /// <param name="strContent">要解密字符</param>
        /// <param name="strKey">加密時使用的鍵值</param>
        /// <returns></returns>
        public static string DeCrypt(string strContent, string strKey)
        {
            if (string.IsNullOrEmpty(strContent)) return string.Empty;
            if (strKey.Length > 8) strKey = strKey.Substring(0, 8); else strKey = KEY_64;
            byte[] byKey = System.Text.ASCIIEncoding.ASCII.GetBytes(strKey);
            byte[] byIV = System.Text.ASCIIEncoding.ASCII.GetBytes(IV_64);

            byte[] byEnc;
            try
            {
                byEnc = Convert.FromBase64String(strContent);
            }
            catch
            {
                return null;
            }

            DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider();
            MemoryStream ms = new MemoryStream(byEnc);
            CryptoStream cst = new CryptoStream(ms, cryptoProvider.CreateDecryptor(byKey, byIV), CryptoStreamMode.Read);
            StreamReader sr = new StreamReader(cst);
            return sr.ReadToEnd();
        }
View Code

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM