对字符串进行加密解密知识

CryptoStream..::.FlushFinalBlock 方法

用缓冲区的当前状态更新基础数据源或储存库,随后清除缓冲区。

Convert..::.ToBase64String 方法    将 8 位无符号整数数组的值转换为它的等效 String 表示形式(使用 Base 64 数字编码)。

代码

 public class Encrypt
    {
        internal string ToEncrypt(string encryptKey, string str)
        {
            try
            {
                byte[] P_byte_key = Encoding.Unicode.GetBytes(encryptKey);//将密钥字符串转换为字节序列
                byte[] P_byte_data = Encoding.Unicode.GetBytes(str);//将字符串转换为字节序列
                MemoryStream P_Stream_MS = new MemoryStream();//创建内存流对象
                CryptoStream P_CryptStream_Stream = //创建加密流对象
                    new CryptoStream(P_Stream_MS, new DESCryptoServiceProvider().CreateEncryptor(P_byte_key, P_byte_key), CryptoStreamMode.Write);
                P_CryptStream_Stream.Write(P_byte_data, 0, P_byte_data.Length);//向加密流中写入字节序列
                P_CryptStream_Stream.FlushFinalBlock();//将数据压入基础流
                byte[] P_bt_temp = P_Stream_MS.ToArray();//从内存流中获取字节序列
                P_CryptStream_Stream.Close();//关闭加密流
                P_Stream_MS.Close();//关闭内存流
                return Convert.ToBase64String(P_bt_temp);
            }
            catch (CryptographicException ce)
            {

                throw new Exception(ce.Message);
            }
        }

        internal string ToDecrypt(string encryptKey, string str)
        {
            try
            {
                byte[] P_byte_key = Encoding.Unicode.GetBytes(encryptKey);
                byte[] P_byte_data = Convert.FromBase64String(str);//将加密后的字符串转换成字节序列
                MemoryStream P_Stream_MS = new MemoryStream(P_byte_data);//创建内存流并写入数据
                CryptoStream P_CryptStream_Stream = new CryptoStream(P_Stream_MS, new DESCryptoServiceProvider().CreateDecryptor(P_byte_key, P_byte_key), CryptoStreamMode.Read);//创建加密流对象
                byte[] P_bt_temp = new byte[200];//创建字节流对象
                MemoryStream P_MemoryStream_temp = new MemoryStream();//创建内存流对象
                int i = 0;//创建计数器
                while((i = P_CryptStream_Stream.Read(P_bt_temp, 0, P_bt_temp.Length)) > 0)//使用while循环得到解密流数据
                {
                    P_MemoryStream_temp.Write(P_bt_temp, 0, i);//将解密后的数据放入内存流
                }
                return Encoding.Unicode.GetString(P_MemoryStream_temp.ToArray());//方法返回解密后的字符串
            }
            catch(CryptographicException ce)
            {
                throw new Exception(ce.Message);
            }
        }
原文地址:https://www.cnblogs.com/bedfly/p/12590248.html