DES 加密解密

来源:互联网 发布:淘宝买家秀福利百度云 编辑:程序博客网 时间:2024/06/09 18:55


/// <summary>
         /// 对字符串进行DES加密
        /// </summary>
         /// <param name="encryptString">将要加密的字符串</param>
         /// <param name="encryptKey">密钥值(需为8位字符串)</param>
        /// <param name="ivkey">初始化向量</param>
        /// <returns></returns>
        public  string EncryptDES(string encryptString, string encryptKey, string ivkey)
         {
             byte[] data = Encoding.ASCII.GetBytes(encryptString);
             DESCryptoServiceProvider DES = new DESCryptoServiceProvider();
             DES.Key = ASCIIEncoding.ASCII.GetBytes(encryptKey);
             DES.IV = ASCIIEncoding.ASCII.GetBytes(ivkey);
             MemoryStream ms = new MemoryStream();  //创建其支持存储区为内存的流。
             CryptoStream cs = new CryptoStream(ms, DES.CreateEncryptor(), CryptoStreamMode.Write);//将数据流连接到加密转换流
             cs.Write(data, 0, data.Length);
             cs.FlushFinalBlock();  //用缓冲区的当前状态更新基础数据源或储存库,随后清除缓
             StringBuilder ret = new StringBuilder();
             foreach (byte b in ms.ToArray())
             {
                 ret.AppendFormat("{0:X2}", b);
             }
             return ret.ToString();
 
         }

        /// <summary>
        /// 对字符串进行DES解密
        /// </summary>
        /// <param name="decryptString">将要解密的字符串</param>
        /// <param name="decryptKey">密钥值(需为8位字符串)</param>
        /// <param name="ivkey">初始化向量</param>
        /// <returns></returns>
        public string DecryptDES(string decryptString, string decryptKey, string ivkey)
        {
            DESCryptoServiceProvider des = new DESCryptoServiceProvider();

            //Put  the  input  string  into  the  byte  array 
            byte[] inputByteArray = new byte[decryptString.Length / 2];
            for (int x = 0; x < decryptString.Length; x += 2)
            {
                int i = Convert.ToInt32(decryptString.Substring(x, 2), 16);
                inputByteArray[x / 2] = (byte)i;
            }

            des.Key = ASCIIEncoding.ASCII.GetBytes(decryptKey);
            des.IV = ASCIIEncoding.ASCII.GetBytes(ivkey);
            MemoryStream ms = new MemoryStream();
            CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write);
            cs.Write(inputByteArray, 0, inputByteArray.Length);
            cs.FlushFinalBlock();
            //建立StringBuild对象,CreateDecrypt使用的是流对象,必须把解密后的文本变成流对象 
            StringBuilder ret = new StringBuilder();
            return System.Text.Encoding.UTF8.GetString(ms.ToArray());
        }

    }

0 0