DES加密解密

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace PingDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("请输入字符串:");
            var str = Console.ReadLine();
            Console.WriteLine("加密后的字符串:");
            Console.WriteLine(Encrypt(str));
            Console.WriteLine("解密后的字符串:");
            Console.WriteLine(Decrypt(Encrypt(str)));
            Console.ReadLine();
        }

        static string encryptKey = "eKey";    //定义密钥  

        #region 加密字符串
        /// <summary> /// 加密字符串   
        /// </summary>  
        /// <param name="str">要加密的字符串</param>  
        /// <returns>加密后的字符串</returns>  
        static string Encrypt(string str)
        {
            DESCryptoServiceProvider descsp = new DESCryptoServiceProvider();   //实例化加/解密类对象   

            byte[] key = Encoding.Unicode.GetBytes(encryptKey); //定义字节数组,用来存储密钥    

            byte[] data = Encoding.Unicode.GetBytes(str);//定义字节数组,用来存储要加密的字符串  

            MemoryStream mStream = new MemoryStream(); //实例化内存流对象      

            //使用内存流实例化加密流对象   
            CryptoStream cStream = new CryptoStream(mStream, descsp.CreateEncryptor(key, key), CryptoStreamMode.Write);

            cStream.Write(data, 0, data.Length);  //向加密流中写入数据      

            cStream.FlushFinalBlock();              //释放加密流      

            return Convert.ToBase64String(mStream.ToArray());//返回加密后的字符串  
        }
        #endregion

        #region 解密字符串
        /// <summary>  
        /// 解密字符串   
        /// </summary>  
        /// <param name="str">要解密的字符串</param>  
        /// <returns>解密后的字符串</returns>  
        static string Decrypt(string str)
        {
            DESCryptoServiceProvider descsp = new DESCryptoServiceProvider();   //实例化加/解密类对象    

            byte[] key = Encoding.Unicode.GetBytes(encryptKey); //定义字节数组,用来存储密钥    

            byte[] data = Convert.FromBase64String(str);//定义字节数组,用来存储要解密的字符串  

            MemoryStream mStream = new MemoryStream(); //实例化内存流对象      

            //使用内存流实例化解密流对象       
            CryptoStream cStream = new CryptoStream(mStream, descsp.CreateDecryptor(key, key), CryptoStreamMode.Write);

            cStream.Write(data, 0, data.Length);      //向解密流中写入数据     

            cStream.FlushFinalBlock();               //释放解密流      

            return Encoding.Unicode.GetString(mStream.ToArray());       //返回解密后的字符串  
        }
        #endregion
    }
}

需要注意的是:CreateDecryptor时,rgbKey必须为8位byte数组,rgbIV必须为大于等于8位byte数组。

否则会出现“指定键的大小对于此算法无效。”或“指定的初始化向量(IV)与此算法的块大小不匹配。”的错误

posted @ 2016-11-03 10:21  bky_xiaozhu  阅读(379)  评论(0编辑  收藏  举报