DES加解密实现方式

private static readonly byte[] _keys = { 0x22, 0x84, 0x56, 0x98, 0x90, 0xAB, 0xpD, 0xEF };
        private static readonly byte[] _ivs = { 0xAB, 0xCD, 0xEF, 0x12, 0x34, 0x56, 0x78, 0x90 };
        /// <summary>
        /// 加密字符串
        /// </summary>
        /// <param name="pToEncrypt">待加密字符串</param>
        /// <returns></returns>
        public string Encrypt(string pToEncrypt)
        {
            var des = new DESCryptoServiceProvider();
            try
            {
                var inputByteArray = Encoding.UTF8.GetBytes(pToEncrypt);
                des.Key = _keys;
                des.IV = _ivs;
                var ms = new MemoryStream();
                var cs = new CryptoStream(ms, des.CreateEncryptor(),
                CryptoStreamMode.Write);
                cs.Write(inputByteArray, 0, inputByteArray.Length);
                cs.FlushFinalBlock();
                var ret = new StringBuilder();
                foreach (byte b in ms.ToArray())
                {
                    ret.AppendFormat("{0:X2}", b);
                }

                return ret.ToString();
            }
            catch
            {
                return pToEncrypt;
            }
            finally
            {
                des = null;
            }
        }

        /// <summary>
        /// 解密字符串
        /// </summary>
        /// <param name="pToDecrypt">待解密字符串</param>
        /// <returns></returns>
        public string Decrypt(string pToDecrypt)
        {
            var des = new DESCryptoServiceProvider();
            try
            {
                var inputByteArray = new byte[pToDecrypt.Length / 2];
                for (var x = 0; x < pToDecrypt.Length / 2; x++)
                {
                    var i = (Convert.ToInt32(pToDecrypt.Substring(x * 2, 2), 16));
                    inputByteArray[x] = (byte)i;
                }

                //建立加密对象的密钥和偏移量
                des.Key = _keys;
                des.IV = _ivs;
                var ms = new MemoryStream();
                var cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write);
                cs.Write(inputByteArray, 0, inputByteArray.Length);
                cs.FlushFinalBlock();
                return Encoding.UTF8.GetString(ms.ToArray());
            }
            catch
            {
                return pToDecrypt;
            }
            finally
            {
                des = null;
            }
        }
原文地址:https://www.cnblogs.com/cr7/p/3183899.html