c# DES加密解密

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了c# DES加密解密相关的知识,希望对你有一定的参考价值。

 class DESHelper
    {

        string _iv = "9AUP";
        string _key = "9d";

        /// <summary>
        /// DES加密偏移量,必须是>=8位长的字符串
        /// </summary>
        public string Iv
        {
            get { return _iv; }
            set { _iv = value; }
        }

        /// <summary>
        /// DES加密的私钥,必须是8位长的字符串
        /// </summary>
        public string Key
        {
            get { return _key; }
            set { _key = value; }
        }

        /// <summary>
        /// 对字符串进行DES加密
        /// </summary>
        /// <param name="sourceString">待加密的字符串</param>
        /// <returns>加密后的BASE64编码的字符串</returns>
        public string Encrypt(string sourceString)
        {
            byte[] btKey = Encoding.Default.GetBytes(_key);
            byte[] btIv = Encoding.Default.GetBytes(_iv);
            var des = new DESCryptoServiceProvider();
            using (var ms = new MemoryStream())
            {
                byte[] inData = Encoding.Default.GetBytes(sourceString);
                try
                {
                    using (var cs = new CryptoStream(ms, des.CreateEncryptor(btKey, btIv), CryptoStreamMode.Write))
                    {
                        cs.Write(inData, 0, inData.Length);
                        cs.FlushFinalBlock();
                    }

                    return Convert.ToBase64String(ms.ToArray());
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
        }

        /// <summary>
        /// 对DES加密后的字符串进行解密
        /// </summary>
        /// <param name="encryptedString">待解密的字符串</param>
        /// <returns>解密后的字符串</returns>
        public string Decrypt(string encryptedString)
        {
            byte[] btKey = Encoding.Default.GetBytes(_key);
            byte[] btIv = Encoding.Default.GetBytes(_iv);
            var des = new DESCryptoServiceProvider();

            using (var ms = new MemoryStream())
            {
                try
                {
                    byte[] inData = Convert.FromBase64String(encryptedString);
                    using (var cs = new CryptoStream(ms, des.CreateDecryptor(btKey, btIv), CryptoStreamMode.Write))
                    {
                        cs.Write(inData, 0, inData.Length);
                        cs.FlushFinalBlock();
                    }

                    return Encoding.Default.GetString(ms.ToArray());
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
        }
    }

  

以上是关于c# DES加密解密的主要内容,如果未能解决你的问题,请参考以下文章

C# 程序密码用des加密源代码

C# DES加密解密问题

一个java的DES加解密类转换成C#

DES加密解密问题,java 和 C#

c# 做一个DES算法加密解密的窗体

使用C# DES解密java DES加密的字符串