C# DES对称加密解密

        /// <summary>
        /// 加密
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        private string Encryption(string str)
        {
            string psw;
            string key = "tracymac";
            using (DESCryptoServiceProvider des = new DESCryptoServiceProvider())
            {
                byte[] inputByteArray = Encoding.UTF8.GetBytes(str);
                des.Key = ASCIIEncoding.ASCII.GetBytes(key);
                des.IV = ASCIIEncoding.ASCII.GetBytes(key);
                System.IO.MemoryStream ms = new System.IO.MemoryStream();
                using (CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write))
                {
                    cs.Write(inputByteArray, 0, inputByteArray.Length);
                    cs.FlushFinalBlock();
                    cs.Close();
                }
                psw = Convert.ToBase64String(ms.ToArray());
                ms.Close();                
            }
            return psw;
        }

        /// <summary>
        /// 解密
        /// </summary>
        /// <param name="psw"></param>
        /// <returns></returns>
        private string Decode(string psw)
        {
            string str;
            string key = "tracymac";
            using (DESCryptoServiceProvider des = new DESCryptoServiceProvider())
            {
                byte[] inputByteArray = Convert.FromBase64String(psw);
                des.Key = ASCIIEncoding.ASCII.GetBytes(key);
                des.IV = ASCIIEncoding.ASCII.GetBytes(key);
                System.IO.MemoryStream ms = new System.IO.MemoryStream();
                using (CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write))
                {
                    cs.Write(inputByteArray, 0, inputByteArray.Length);
                    cs.FlushFinalBlock();
                    cs.Close();
                }
                str = Encoding.UTF8.GetString(ms.ToArray());
                ms.Close();                
            }
            return str;
        }

 

更多个人工作中的项目请访问我的个人网站:www.88gis.cn

上一篇:.net MVC 使用 JSON JavaScriptSerializer 进行序列化或反序列化时出错,字符串的长度超过了为 maxJsonLength 属性设置的值


下一篇:XWalkView+html 开发Android应用