zoukankan      html  css  js  c++  java
  • C#将字节流加密解密

    public class Encrypt
        {
            public static byte[] ToEncrypt(string encryptKey, byte[] P_byte_data)
            {
                try
                {
                    byte[] P_byte_key = Encoding.Unicode.GetBytes(encryptKey);//将密钥字符串转换为字节序列
                    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 P_bt_temp;//方法返回加密后的byte 
                }
                catch (CryptographicException ce)
                {
                    throw new Exception(ce.Message);
                }
            }
    
            public static byte[] ToDecrypt(string encryptKey, byte[] P_byte_data)
            {
                try
                {
                    byte[] P_byte_key = Encoding.Unicode.GetBytes(encryptKey); //将密钥字符串转换为字节序列
                    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 P_MemoryStream_temp.ToArray();//方法返回解密后的byte
                        
                }
                catch (CryptographicException ce)
                {
                    throw new Exception(ce.Message);
                }
            }
    View Code
  • 相关阅读:
    Python+Selenium自动化总结
    Python+Selenium自动化-定位一组元素,单选框、复选框的选中方法
    Python+Selenium自动化-模拟键盘操作
    【leetcode】1053. Previous Permutation With One Swap
    【leetcode】1052. Grumpy Bookstore Owner
    【leetcode】1034. Coloring A Border
    【leetcode】1042. Flower Planting With No Adjacent
    【leetcode】1035. Uncrossed Lines
    【leetcode】1048. Longest String Chain
    【leetcode】1047. Remove All Adjacent Duplicates In String
  • 原文地址:https://www.cnblogs.com/aweifly/p/3410852.html
Copyright © 2011-2022 走看看