最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

C#使用CryptoStream類加密和解密字符串的實(shí)現(xiàn)

 更新時(shí)間:2024年01月22日 09:39:51   作者:wenchm  
CryptoStream設(shè)計(jì)用于在內(nèi)容以流的形式輸出到文件時(shí)加密和解密內(nèi)容,本文主要介紹了C#使用CryptoStream類加密和解密字符串的實(shí)現(xiàn),具有一定的參考價(jià)值,感興趣的可以了解一下

 在使用CryptoStream前要先引用命名空間using System.Security.Cryptography。

一、CrytoStream的加密方法

記住,不能再使用DESCryptoServiceProvider().CreateEncryptor()創(chuàng)建加密流,因?yàn)樗呀?jīng)被微軟廢棄了。會(huì)提示“SYSLIB0021:派生加密類型已過(guò)時(shí)”,編譯也過(guò)不去。

SYSLIB0021 警告 - .NET | Microsoft Learn  

https://learn.microsoft.com/zh-cn/dotnet/fundamentals/syslib-diagnostics/syslib0021

解決辦法:把DESCryptoServiceProvider().CreateEncryptor()替換為DES.Create()。

internal static string ToEncrypt(string encryptKey, string str)
{
    try
    {
        byte[] byte_key = Encoding.Unicode.GetBytes(encryptKey);    //將密鑰字符串轉(zhuǎn)換為字節(jié)序列
        byte[] byte_data = Encoding.Unicode.GetBytes(str);          //將字符串轉(zhuǎn)換為字節(jié)序列     
        using var des = DES.Create();                               //創(chuàng)建加密流對(duì)象
        using var memory_stream = new MemoryStream();               //創(chuàng)建內(nèi)存流對(duì)象
        using var crypto_stream = new CryptoStream(memory_stream, des.
            CreateEncryptor(byte_key, byte_key), CryptoStreamMode.Write); //創(chuàng)建加密流對(duì)象
        crypto_stream.Write(byte_data, 0, byte_data.Length);        //向加密流中寫入字節(jié)序列
        crypto_stream.FlushFinalBlock();                            //將數(shù)據(jù)壓入基礎(chǔ)流
        crypto_stream.Close();                                      //關(guān)閉加密流
        memory_stream.Close();                                      //關(guān)閉內(nèi)存流
        return Convert.ToBase64String(memory_stream.ToArray());     //從內(nèi)存流中獲取并返回加密后的字符串
    }
    catch (CryptographicException ce)
    {
        throw new Exception(ce.Message);
    }
}

二、CrytoStream的解密方法

與加密方法具有相同的注意事項(xiàng)。

internal static string ToDecrypt(string encryptKey, string str)
{
    try
    {
        byte[] byte_key = Encoding.Unicode.GetBytes(encryptKey);          //將密鑰字符串轉(zhuǎn)換為字節(jié)序列
        byte[] byte_data = Convert.FromBase64String(str);                                  //將加密后的字符串轉(zhuǎn)換為字節(jié)序列
        using var des = DES.Create();                                                                  //創(chuàng)建加密流對(duì)象
        using var memory_stream = new MemoryStream(byte_data);            //創(chuàng)建內(nèi)存流對(duì)象并寫入數(shù)據(jù)
        using var crypto_stream = new CryptoStream(memory_stream, des.
            CreateDecryptor(byte_key, byte_key), CryptoStreamMode.Read);  //創(chuàng)建加密流對(duì)象
        byte[] bt_temp = new byte[200];                                                             //創(chuàng)建字節(jié)序列對(duì)象
        MemoryStream memory_stream_temp = new();                          //創(chuàng)建內(nèi)存流對(duì)象
        int i = 0;                                                                                                 //創(chuàng)建記數(shù)器
        while ((i = crypto_stream.Read(bt_temp, 0, bt_temp.Length)) > 0)  //使用while循環(huán)得到解密數(shù)據(jù)
        {
            memory_stream_temp.Write(bt_temp, 0, i);                                        //將解密后的數(shù)據(jù)放入內(nèi)存流
        }
        crypto_stream.Close();                                                                           //關(guān)閉加密流
        memory_stream.Close();                                                                        //關(guān)閉內(nèi)存流
        return Encoding.Unicode.GetString(memory_stream_temp.ToArray());    //方法返回解密后的字符串
    }
    catch (CryptographicException ce)
    {
        throw new Exception(ce.Message);
    }
}

三、實(shí)例

對(duì)字符串加密、解密的實(shí)例,秘鑰=4位數(shù)字。

1.源碼Form1.cs

// 使用CryptoStream類加密和解密字符串
namespace _046
{
    public partial class Form1 : Form
    {
        private GroupBox? groupBox1;
        private GroupBox? groupBox2;
        private Button? button1;
        private TextBox? textBox3;
        private TextBox? textBox2;
        private TextBox? textBox1;
        private Label? label3;
        private Label? label2;
        private Label? label1;
        private Button? button2;
        private TextBox? textBox6;
        private Label? label4;
        private Label? label5;
        private Label? label6;
        private TextBox? textBox4;
        private TextBox? textBox5;

        public Form1()
        {
            InitializeComponent();
            Load += Form1_Load;
        }
        private void Form1_Load(object? sender, EventArgs e)
        {
            // 
            // button1
            // 
            button1 = new Button
            {
                Location = new Point(369, 89),
                Name = "button1",
                Size = new Size(75, 23),
                TabIndex = 6,
                Text = "加密",
                UseVisualStyleBackColor = true
            };
            button1.Click += Button1_Click;
            // 
            // textBox3
            //           
            textBox3 = new TextBox
            {
                Location = new Point(12, 136),
                Multiline = true,
                Name = "textBox3",
                Size = new Size(432, 46),
                TabIndex = 5
            };
            // 
            // textBox2
            //          
            textBox2 = new TextBox
            {
                Location = new Point(119, 89),
                Name = "textBox2",
                Size = new Size(244, 23),
                TabIndex = 4
            };
            // 
            // textBox1
            //           
            textBox1 = new TextBox
            {
                Location = new Point(11, 41),
                Multiline = true,
                Name = "textBox1",
                Size = new Size(433, 46),
                TabIndex = 3
            };
            // 
            // label3
            //            
            label3 = new Label
            {
                AutoSize = true,
                Location = new Point(11, 114),
                Name = "label3",
                Size = new Size(92, 17),
                TabIndex = 2,
                Text = "加密后字符串:"
            };
            // 
            // label2
            //            
            label2 = new Label
            {
                AutoSize = true,
                Location = new Point(11, 92),
                Name = "label2",
                Size = new Size(81, 17),
                TabIndex = 1,
                Text = "4bit加密秘鑰:"
            };
            // 
            // label1
            //             
            label1 = new Label
            {
                AutoSize = true,
                Location = new Point(11, 19),
                Name = "label1",
                Size = new Size(92, 17),
                TabIndex = 0,
                Text = "加密前字符串:"
            };
            // 
            // groupBox1
            // 
            groupBox1 = new GroupBox
            {
                Location = new Point(12, 12),
                Name = "groupBox1",
                Size = new Size(450, 188),
                TabIndex = 0,
                TabStop = false,
                Text = "加密"
            };
            groupBox1.Controls.Add(button1);
            groupBox1.Controls.Add(textBox3);
            groupBox1.Controls.Add(textBox2);
            groupBox1.Controls.Add(textBox1);
            groupBox1.Controls.Add(label3);
            groupBox1.Controls.Add(label2);
            groupBox1.Controls.Add(label1);
            groupBox1.SuspendLayout();
            // 
            // button2
            //
            button2 = new Button
            {
                Location = new Point(369, 89),
                Name = "button2",
                Size = new Size(75, 23),
                TabIndex = 13,
                Text = "解密",
                UseVisualStyleBackColor = true
            };
            button2.Click += Button2_Click;
            // 
            // textBox6
            //           
            textBox6 = new TextBox
            {
                Location = new Point(12, 136),
                Multiline = true,
                Name = "textBox6",
                Size = new Size(433, 46),
                TabIndex = 12
            };
            // 
            // label4
            //           
            label4 = new Label
            {
                AutoSize = true,
                Location = new Point(12, 19),
                Name = "label4",
                Size = new Size(92, 17),
                TabIndex = 7,
                Text = "解密前字符串:"
            };
            // 
            // label5
            //            
            label5 = new Label
            {
                AutoSize = true,
                Location = new Point(12, 92),
                Name = "label5",
                Size = new Size(90, 17),
                TabIndex = 8,
                Text = "4bit解密密鑰:"
            };
            // 
            // label6
            //           
            label6 = new Label
            {
                AutoSize = true,
                Location = new Point(12, 114),
                Name = "label6",
                Size = new Size(92, 17),
                TabIndex = 9,
                Text = "解密后字符串:"
            };
            // 
            // textBox4
            //          
            textBox4 = new TextBox
            {
                Location = new Point(12, 41),
                Multiline = true,
                Name = "textBox4",
                Size = new Size(432, 46),
                TabIndex = 10
            };
            // 
            // textBox5
            //           
            textBox5 = new TextBox
            {
                Location = new Point(119, 89),
                Name = "textBox5",
                Size = new Size(244, 23),
                TabIndex = 11
            };
            // 
            // groupBox2
            // 
            groupBox2 = new GroupBox
            {
                Location = new Point(12, 206),
                Name = "groupBox2",
                Size = new Size(450, 188),
                TabIndex = 0,
                TabStop = false,
                Text = "解密"
            };
            groupBox2.Controls.Add(button2);
            groupBox2.Controls.Add(textBox6);
            groupBox2.Controls.Add(label4);
            groupBox2.Controls.Add(label5);
            groupBox2.Controls.Add(label6);
            groupBox2.Controls.Add(textBox4);
            groupBox2.Controls.Add(textBox5);
            groupBox2.SuspendLayout();

            // 
            // Form1
            // 
            AutoScaleDimensions = new SizeF(7F, 17F);
            AutoScaleMode = AutoScaleMode.Font;
            ClientSize = new Size(474, 406);
            Controls.Add(groupBox2);
            Controls.Add(groupBox1);
            Name = "Form1";
            StartPosition = FormStartPosition.CenterScreen;
            Text = "用CryptoStream類加密和解密字符串";
            groupBox1.ResumeLayout(false);
            groupBox1.PerformLayout();
            groupBox2.ResumeLayout(false);
            groupBox2.PerformLayout();
            ResumeLayout(false);
        }

        private void Button1_Click(object? sender, EventArgs e)
        {
            if (textBox2!.Text.Length == 4)    //判斷加密密鑰長(zhǎng)度是否正確
            {
                try
                {
                    textBox3!.Text =           //調(diào)用實(shí)例ToEncrypt方法得到加密后的字符串
                        Encrypt.ToEncrypt(textBox2.Text, textBox1!.Text);
                }
                catch (Exception ex)            //捕獲異常
                {
                    MessageBox.Show(ex.Message);//輸出異常信息
                }
            }
            else
            {
                MessageBox.Show("密鑰長(zhǎng)度不符!", "提示");//提示用戶輸入密鑰長(zhǎng)度不正確
            }
        }

        private void Button2_Click(object? sender, EventArgs e)
        {
            if (textBox5!.Text.Length == 4)       //判斷加密密鑰長(zhǎng)度是否正確
            {
                try
                {
                    textBox6!.Text =              //調(diào)用ToDecrypt方法得到解密后的字符串
                        Encrypt.ToDecrypt(textBox5.Text, textBox4!.Text);
                }
                catch (Exception ex)              //捕獲異常
                {
                    MessageBox.Show(ex.Message);  //輸出異常信息
                }
            }
            else
            {
                MessageBox.Show("密鑰長(zhǎng)度不符!", "提示");//提示用戶輸入密鑰長(zhǎng)度不正確
            }
        }
    }
}

2.類庫(kù)Encrypt.cs

using System.Security.Cryptography;
using System.Text;

namespace _046
{
    internal class Encrypt
    {
        internal static string ToEncrypt(string encryptKey, string str)
        {
            try
            {
                byte[] byte_key = Encoding.Unicode.GetBytes(encryptKey);//將密鑰字符串轉(zhuǎn)換為字節(jié)序列
                byte[] byte_data = Encoding.Unicode.GetBytes(str);      //將字符串轉(zhuǎn)換為字節(jié)序列     
                using var des = DES.Create();                           //創(chuàng)建加密流對(duì)象                                                
                using var memory_stream = new MemoryStream();           //創(chuàng)建內(nèi)存流對(duì)象
                using var crypto_stream = new CryptoStream(memory_stream, des.
                    CreateEncryptor(byte_key, byte_key), CryptoStreamMode.Write); //創(chuàng)建加密流對(duì)象
                crypto_stream.Write(byte_data, 0, byte_data.Length);    //向加密流中寫入字節(jié)序列
                crypto_stream.FlushFinalBlock();                        //將數(shù)據(jù)壓入基礎(chǔ)流                                            
                crypto_stream.Close();                                  //關(guān)閉加密流                                                         
                memory_stream.Close();                                  //關(guān)閉內(nèi)存流                                                     
                return Convert.ToBase64String(memory_stream.ToArray()); //從內(nèi)存流中獲取并返回加密后的字符串
            }
            catch (CryptographicException ce)
            {
                throw new Exception(ce.Message);
            }
        }

        internal static string ToDecrypt(string encryptKey, string str)
        {
            try
            {
                byte[] byte_key = Encoding.Unicode.GetBytes(encryptKey); //將密鑰字符串轉(zhuǎn)換為字節(jié)序列                  
                byte[] byte_data = Convert.FromBase64String(str);        //將加密后的字符串轉(zhuǎn)換為字節(jié)序列                                  
                using var des = DES.Create();                            //創(chuàng)建加密流對(duì)象                                                                  
                using var memory_stream = new MemoryStream(byte_data);   //創(chuàng)建內(nèi)存流對(duì)象并寫入數(shù)據(jù)                  
                using var crypto_stream = new CryptoStream(memory_stream, des.
                    CreateDecryptor(byte_key, byte_key), CryptoStreamMode.Read);//創(chuàng)建加密流對(duì)象        
                byte[] bt_temp = new byte[200];             //創(chuàng)建字節(jié)序列對(duì)象                                                             
                MemoryStream memory_stream_temp = new();    //創(chuàng)建內(nèi)存流對(duì)象                                     
                int i = 0;                                  //創(chuàng)建記數(shù)器                                                                                                 
                while ((i = crypto_stream.Read(bt_temp, 0, bt_temp.Length)) > 0)//使用while循環(huán)得到解密數(shù)據(jù)           
                {
                    memory_stream_temp.Write(bt_temp, 0, i);//將解密后的數(shù)據(jù)放入內(nèi)存流                                        
                }
                crypto_stream.Close();                       //關(guān)閉加密流                                                                           
                memory_stream.Close();                       //關(guān)閉內(nèi)存流                                                                       
                return Encoding.Unicode.GetString(memory_stream_temp.ToArray());//方法返回解密后的字符串
            }
            catch (CryptographicException ce)
            {
                throw new Exception(ce.Message);
            }
        }
    }
}

3.生成效果 

到此這篇關(guān)于C#使用CryptoStream類加密和解密字符串的實(shí)現(xiàn)的文章就介紹到這了,更多相關(guān)C# CryptoStream加密解密字符串內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • C#集合Collections購(gòu)物車Shopping Cart(實(shí)例講解)

    C#集合Collections購(gòu)物車Shopping Cart(實(shí)例講解)

    下面小編就為大家分享一篇C#集合Collections購(gòu)物車Shopping Cart的實(shí)例講解,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧
    2017-12-12
  • C#中實(shí)現(xiàn)查找mysql的安裝路徑

    C#中實(shí)現(xiàn)查找mysql的安裝路徑

    這篇文章主要介紹了C#中實(shí)現(xiàn)查找mysql的安裝路徑,本文講解使用SQL語(yǔ)句查詢出mysql的安裝路徑,方便在備份時(shí)使用,需要的朋友可以參考下
    2015-06-06
  • C#爬取動(dòng)態(tài)網(wǎng)頁(yè)上信息得流程步驟

    C#爬取動(dòng)態(tài)網(wǎng)頁(yè)上信息得流程步驟

    動(dòng)態(tài)內(nèi)容網(wǎng)站使用 JavaScript 腳本動(dòng)態(tài)檢索和渲染數(shù)據(jù),爬取信息時(shí)需要模擬瀏覽器行為,否則獲取到的源碼基本是空的,這篇文章主要給大家詳細(xì)介紹了C#爬取動(dòng)態(tài)網(wǎng)頁(yè)上信息得流程步驟,需要的朋友可以參考下
    2024-10-10
  • C#中Lambda表達(dá)式的用法

    C#中Lambda表達(dá)式的用法

    這篇文章介紹了C#中Lambda表達(dá)式的用法,文中通過(guò)示例代碼介紹的非常詳細(xì)。對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2022-05-05
  • WPF自定義實(shí)現(xiàn)雷達(dá)圖控件的示例詳解

    WPF自定義實(shí)現(xiàn)雷達(dá)圖控件的示例詳解

    雷達(dá)圖用于表示不同內(nèi)容的占比關(guān)系,在項(xiàng)目中有廣泛的應(yīng)用,但是目前未曾有封裝良好的雷達(dá)圖控件,所以本文分享了如何封裝一個(gè)通用的雷達(dá)圖控件,希望對(duì)大家有所幫助
    2023-08-08
  • 深入理解C#管道式編程

    深入理解C#管道式編程

    這篇文章主要給大家介紹了關(guān)于C#管道式編程的介紹與實(shí)現(xiàn)方法,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家學(xué)習(xí)或者使用C#具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2021-07-07
  • C# ComboBox的聯(lián)動(dòng)操作(三層架構(gòu))

    C# ComboBox的聯(lián)動(dòng)操作(三層架構(gòu))

    這篇文章主要介紹了C# ComboBox的聯(lián)動(dòng)操作(三層架構(gòu)),根據(jù)下拉框的變化使得下拉框綁定對(duì)應(yīng)值,感興趣的小伙伴們可以參考一下
    2016-05-05
  • c#典型工廠化實(shí)現(xiàn)實(shí)例

    c#典型工廠化實(shí)現(xiàn)實(shí)例

    c#典型工廠化實(shí)現(xiàn)實(shí)例,需要的朋友可以參考一下
    2013-03-03
  • C#調(diào)用Oracle存儲(chǔ)過(guò)程方法介紹(附源碼)

    C#調(diào)用Oracle存儲(chǔ)過(guò)程方法介紹(附源碼)

    這篇文章介紹了C#調(diào)用Oracle存儲(chǔ)過(guò)程的方法,文中通過(guò)示例代碼介紹的非常詳細(xì)。對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2022-03-03
  • Unity3D實(shí)現(xiàn)描邊框效果

    Unity3D實(shí)現(xiàn)描邊框效果

    這篇文章主要為大家詳細(xì)介紹了Unity3D實(shí)現(xiàn)描邊框效果,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2020-04-04

最新評(píng)論

博客| 胶州市| 巨野县| 志丹县| 扎囊县| 南乐县| 察哈| 孝感市| 许昌县| 新营市| 高唐县| 横山县| 太仓市| 辉县市| 江门市| 察雅县| 曲阳县| 谷城县| 石阡县| 张家川| 浮梁县| 巨野县| 永安市| 南靖县| 浙江省| 诸暨市| 白山市| 柳河县| 元氏县| 三原县| 旺苍县| 巴南区| 保靖县| 永泰县| 五原县| 霍州市| 岳普湖县| 边坝县| 娄底市| 四平市| 伊吾县|