DES加密体验

 自上次转帖AES与DES加密解密算法之后,自己也实际去实现了下,发现虽然看上去比较简单,但是实际实现过程中本人碰到的问题确实不少,首先在加密过程中经常碰到数据不正确或密钥长度不正确等问题,经过反复的调试与网上求救,终于把能够成功通过的代码分享来相互学习下。

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

namespace WebCrypto
{
    public class DesCrypto
    {
        private static readonly byte[] bDesKey = Encoding.UTF8.GetBytes("12345678");//密钥
         private static readonly byte[] bDesIV = Encoding.UTF8.GetBytes("abcdefgh");//初始向量

         //加密算法
         public static string Encrypt(string PlainText/*, SymmetricAlgorithm key*/)
        {
            DESCryptoServiceProvider desProvider = new DESCryptoServiceProvider();
            desProvider.Padding = PaddingMode.ISO10126;

            byte[] bEnc = Encoding.UTF8.GetBytes(PlainText);
            MemoryStream ms = new MemoryStream();
            
            //利用密钥加密
              CryptoStream encStream = new CryptoStream(ms, desProvider.CreateEncryptor(bDesKey, bDesIV), CryptoStreamMode.Write);
            encStream.Write(bEnc, 0, bEnc.Length);
            encStream.FlushFinalBlock();

            string strEnc = Convert.ToBase64String(ms.ToArray());
              ms.Close();//关闭流
              encStream.Close();

            return strEnc;
        }

        //解密算法
         public static string Decrypt(string CypherText/*, SymmetricAlgorithm key*/)
        {
            if (CypherText == "")
            {
                return null;//若密码为空
              }

            DESCryptoServiceProvider desProvider = new DESCryptoServiceProvider();
            desProvider.Padding = PaddingMode.ISO10126;
            
            byte[] bDec = Convert.FromBase64String(CypherText);
            MemoryStream ms = new MemoryStream(bDec);//将加密数据转换为数据流,此处开始时未将输入流加载密文数据,因而程序报错数据不正确
                        
             //利用密钥解密            
             CryptoStream encStream = new CryptoStream(ms, desProvider.CreateDecryptor(bDesKey, bDesIV), CryptoStreamMode.Read);
                       
           StreamReader sr = new StreamReader(encStream);//读取数据流内容,采用streamreader方法可以避免密文解密后出现冗余字符的情况
             string strDec = sr.ReadLine();//转换为字符串
                       
           sr.Close();//关闭流
             encStream.Close();
           ms.Close();
                        
           return strDec;
        }

    }
}

你可能感兴趣的:(DES加密体验)