C#-字符串的加解密,DES标准,DESCryptoServiceProvider---ShinePans

//字符串加解密
//GetBytes:将指定字符串中的所有字符编码为一个字节的序列
//CreateEncryptor:用指定的密匙和初始化向量创建对称数据库加密标准(DES)加密器对象
//CreateDecryptor:用指定的密匙和初始化向量创建对称数据加密标准(DES)解密器对象
using System;
using System.Text;
using System.IO;
using System.Security.Cryptography;
class program
{
    static string encryptKey = "Fuck";  //加密密匙
    static void Main()
    {
        Console.WriteLine("Please input sentences");
        string strOld = Console.ReadLine();
        DESCryptoServiceProvider descsp = new DESCryptoServiceProvider();//实例化加解密对象
        
        byte[] key = Encoding.Unicode.GetBytes(encryptKey); //定义字节数组
        byte[] data1=Encoding.Unicode.GetBytes(strOld);
        MemoryStream MStream = new MemoryStream(); //实例化内存流实例
        
        CryptoStream CStream=new CryptoStream(MStream,descsp.CreateEncryptor(key,key),CryptoStreamMode.Write); //向解密流中写入数据
        CStream.Write(data1, 0, data1.Length); //向加密流中写入数据
        CStream.FlushFinalBlock();  //放加密流
        string strEncrypt = Convert.ToBase64String(MStream.ToArray()); //加密字符串
        Console.WriteLine("加密后的字符:"+strEncrypt); //输出加密后的字符
        byte[] data2 = Convert.FromBase64String(strEncrypt); //定义,用来存放待解密的字符串
        MStream = new MemoryStream();  //实例化内存流对象
        CStream = new CryptoStream(MStream, descsp.CreateDecryptor(key, key), CryptoStreamMode.Write);
        CStream.Write(data2, 0, data2.Length);  //向解密流中写入数据
        CStream.FlushFinalBlock(); //放解密流
        string strDecrypt = Encoding.Unicode.GetString(MStream.ToArray());//解密字符串
        Console.WriteLine("解密后的字符串:" + strDecrypt); //输出解密后的字符串
        MStream.Close();   //关闭内存流
        CStream.Close();  // 关闭加解密流

        Console.ReadLine();
    }
}



C#-字符串的加解密,DES标准,DESCryptoServiceProvider---ShinePans_第1张图片

你可能感兴趣的:(C#基础,C#从入门到精通之路)