加密解密,CryptoStream()的使用


一:上圖

二:代碼

主界面代碼

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace StringEncrypt
{
    public partial class Frm_Main : Form
    {
        public Frm_Main()
        {
            InitializeComponent();
        }

        private void btn_Encrypt_Click(object sender, EventArgs e)
        {
            if (txt_password.Text.Length == 4)//判斷加密密鑰長度是否正確
            {
                try
                {
                    txt_EncryptStr.Text = //調用實例ToEncrypt方法得到加密后的字符串
                        new Encrypt().ToEncrypt(
                        txt_password.Text, txt_str.Text);
                    //Encrypt P_Encrypt = new Encrypt();
                    //P_Encrypt.ToEncrypt(""
                }
                catch (Exception ex)//捕獲異常
                {
                    MessageBox.Show(ex.Message);//輸出異常信息
                }
            }
            else
            {
                MessageBox.Show("密鑰長度不符!", "提示");//提示用戶輸入密鑰長度不正確
            }
        }
        private void btn_UnEncrypt_Click(object sender, EventArgs e)
        {
            if (txt_password2.Text.Length == 4)//判斷加密密鑰長度是否正確
            {
                try
                {
                    txt_str2.Text = //調用ToDecrypt方法得到解密后的字符串
                        new Encrypt().ToDecrypt(
                        txt_password2.Text, txt_EncryptStr2.Text);
                }
                catch (Exception ex)//捕獲異常
                {
                    MessageBox.Show(ex.Message);//輸出異常信息
                }
            }
            else
            {
                MessageBox.Show("密鑰長度不符!", "提示");//提示用戶輸入密鑰長度不正確
            }
        }
    }
}

加密解密類代碼

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

namespace StringEncrypt
{
    public class Encrypt
    {
        /// <summary>
        /// 加密
        /// </summary>
        /// <param name="encryptKey">密鑰</param>
        /// <param name="str">信息</param>
        /// <returns></returns>
        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(//使用while循環得到解密數據
                    P_bt_temp, 0, P_bt_temp.Length)) > 0)//(1\從當前流中讀取200個字節-並將它們存儲在 P_bt_temp 中 2\P_bt_temp 中的字節偏移量-從該偏移量開始存儲從當前流中讀取的數據 3\讀入緩沖區中的總字節數)
                {
                    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);
            }
        }
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM