"景先生毕设|www.jxszl.com

C#DES加密和解密代码

2022-12-21 14:33编辑: www.jxszl.com景先生毕设

C#DES加密和解密代码        


一、DES 定义密钥
       private static readonly string DESIV = "Des123";

二、DES 加密代码
        /// <summary>
        /// 加密
        /// </summary>
        /// <param name="originalValue">需要加密字符串</param>
        /// <param name="key">密钥</param>
        /// <returns>加密后的字符串</returns>
        public static string DESEncrypt(string originalValue, string key)
        {
            string result;
            try
            {
                key += "CryDeKey";
                key = key.Substring(0, 8);
                ICryptoTransform transform = new DESCryptoServiceProvider
                {
                    Key = Encoding.UTF8.GetBytes(key),
                    IV = Encoding.UTF8.GetBytes(HisDecrypt.DESIV)
                }.CreateEncryptor();
                byte[] bytes = Encoding.UTF8.GetBytes(originalValue);
                MemoryStream memoryStream = new MemoryStream();
                CryptoStream cryptoStream = new CryptoStream(memoryStream, transform, CryptoStreamMode.Write);
                cryptoStream.Write(bytes, 0, bytes.Length);
                cryptoStream.FlushFinalBlock();
                cryptoStream.Close();
                result = Convert.ToBase64String(memoryStream.ToArray());
            }
            catch
            {
                result = originalValue;
            }
            return result;
        }

二、DES 解密代码
        /// <summary>
        /// 加密
        /// </summary>
        /// <param name="originalValue">需要解密字符串</param>
        /// <param name="key">密钥</param>
        /// <returns>解密后的字符串</returns>
        public static string DESDecrypt(string encryptedValue, string key)
        {
            string result;
            try
            {
                key += "CryDeKey";
                key = key.Substring(0, 8);
                ICryptoTransform transform = new DESCryptoServiceProvider
                {
                    Key = Encoding.UTF8.GetBytes(key),
                    IV = Encoding.UTF8.GetBytes(HisDecrypt.DESIV)
                }.CreateDecryptor();
                byte[] array = Convert.FromBase64String(encryptedValue);
                MemoryStream memoryStream = new MemoryStream();
                CryptoStream cryptoStream = new CryptoStream(memoryStream, transform, CryptoStreamMode.Write);
                cryptoStream.Write(array, 0, array.Length);
                cryptoStream.FlushFinalBlock();
                cryptoStream.Close();
                result = Encoding.UTF8.GetString(memoryStream.ToArray());
            }
            catch
            {
                result = encryptedValue;
            }
            return result;
        }
原文链接:http://www.jxszl.com/biancheng/C/84602.html