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
相關文章
相關標籤/搜索