C# DES 加密解密字符

   public class Decode
    {
        /// <summary>
        /// 算法的机密密钥
        /// 可以重新定义8位 255以内的整型字节组
        /// </summary>
        static byte[] rgbKey = { 56, 104, 247, 80, 34, 88, 157, 4 };
        /// <summary>
        /// 对称算法的初始化向量
        /// 可以重新定义8位 255以内的整型字节组
        /// </summary>
        static byte[] rgbIV = { 101, 18, 99, 166, 98, 6, 151, 36 };

        /// <summary>
        /// 加密
        /// </summary>
        /// <param name="strEncrypt">需要加密的字符串</param>
        /// <returns>加密的字符串</returns>
        public static string Encrypt(string strEncrypt)
        {
            //将要加密的字符串转换成字节数组    
            byte[] bytes = Encoding.Default.GetBytes(strEncrypt);

            // DES创建对称加密器对象 
            DESCryptoServiceProvider des = new DESCryptoServiceProvider();
            des.Key = rgbKey;
            des.IV = rgbIV;
            ICryptoTransform encryptor = des.CreateEncryptor();

            //将要加密的字节数组写入到流中
            MemoryStream ms = new MemoryStream();

            CryptoStream cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write);

            cs.Write(bytes, 0, bytes.Length);
            cs.FlushFinalBlock();

            var str = Convert.ToBase64String(ms.ToArray());
            return str;
        }


        /// <summary>  
        /// 解密  
        /// </summary>  
        /// <param name="strDecrypt">需要解密的字符串</param>  
        /// <returns>解密后的字符串</returns>  

        public static string Decrypt(string strDecrypt)
        {
            //将解密字符串转换成字节数组  
            byte[] bytes = Convert.FromBase64String(strDecrypt);

            //DES创建对称解密器对象
            DESCryptoServiceProvider des = new DESCryptoServiceProvider();
            des.Key = rgbKey;
            des.IV = rgbIV;
            ICryptoTransform encryptor = des.CreateDecryptor();

            //从流中读取解密字符串
            MemoryStream ms = new MemoryStream(bytes, 0, bytes.Length);
        
            CryptoStream cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Read);

            StreamReader sr = new StreamReader(cs, Encoding.Default);

            var str = sr.ReadToEnd();

            return str;
        }
    }

  

posted on 2020-07-03 14:05  走出高度  阅读(210)  评论(0编辑  收藏  举报