C#教程

关注公众号 jb51net

关闭
首页 > 软件编程 > C#教程 > C# CryptoStream加密解密字符串

C#使用CryptoStream类加密和解密字符串的实现

作者:wenchm

CryptoStream设计用于在内容以流的形式输出到文件时加密和解密内容,本文主要介绍了C#使用CryptoStream类加密和解密字符串的实现,具有一定的参考价值,感兴趣的可以了解一下

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

一、CrytoStream的加密方法

记住,不能再使用DESCryptoServiceProvider().CreateEncryptor()创建加密流,因为它已经被微软废弃了。会提示“SYSLIB0021:派生加密类型已过时”,编译也过不去。

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);    //将密钥字符串转换为字节序列
        byte[] byte_data = Encoding.Unicode.GetBytes(str);          //将字符串转换为字节序列     
        using var des = DES.Create();                               //创建加密流对象
        using var memory_stream = new MemoryStream();               //创建内存流对象
        using var crypto_stream = new CryptoStream(memory_stream, des.
            CreateEncryptor(byte_key, byte_key), CryptoStreamMode.Write); //创建加密流对象
        crypto_stream.Write(byte_data, 0, byte_data.Length);        //向加密流中写入字节序列
        crypto_stream.FlushFinalBlock();                            //将数据压入基础流
        crypto_stream.Close();                                      //关闭加密流
        memory_stream.Close();                                      //关闭内存流
        return Convert.ToBase64String(memory_stream.ToArray());     //从内存流中获取并返回加密后的字符串
    }
    catch (CryptographicException ce)
    {
        throw new Exception(ce.Message);
    }
}

二、CrytoStream的解密方法

与加密方法具有相同的注意事项。

internal static string ToDecrypt(string encryptKey, string str)
{
    try
    {
        byte[] byte_key = Encoding.Unicode.GetBytes(encryptKey);          //将密钥字符串转换为字节序列
        byte[] byte_data = Convert.FromBase64String(str);                                  //将加密后的字符串转换为字节序列
        using var des = DES.Create();                                                                  //创建加密流对象
        using var memory_stream = new MemoryStream(byte_data);            //创建内存流对象并写入数据
        using var crypto_stream = new CryptoStream(memory_stream, des.
            CreateDecryptor(byte_key, byte_key), CryptoStreamMode.Read);  //创建加密流对象
        byte[] bt_temp = new byte[200];                                                             //创建字节序列对象
        MemoryStream memory_stream_temp = new();                          //创建内存流对象
        int i = 0;                                                                                                 //创建记数器
        while ((i = crypto_stream.Read(bt_temp, 0, bt_temp.Length)) > 0)  //使用while循环得到解密数据
        {
            memory_stream_temp.Write(bt_temp, 0, i);                                        //将解密后的数据放入内存流
        }
        crypto_stream.Close();                                                                           //关闭加密流
        memory_stream.Close();                                                                        //关闭内存流
        return Encoding.Unicode.GetString(memory_stream_temp.ToArray());    //方法返回解密后的字符串
    }
    catch (CryptographicException ce)
    {
        throw new Exception(ce.Message);
    }
}

三、实例

对字符串加密、解密的实例,秘钥=4位数字。

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)    //判断加密密钥长度是否正确
            {
                try
                {
                    textBox3!.Text =           //调用实例ToEncrypt方法得到加密后的字符串
                        Encrypt.ToEncrypt(textBox2.Text, textBox1!.Text);
                }
                catch (Exception ex)            //捕获异常
                {
                    MessageBox.Show(ex.Message);//输出异常信息
                }
            }
            else
            {
                MessageBox.Show("密钥长度不符!", "提示");//提示用户输入密钥长度不正确
            }
        }

        private void Button2_Click(object? sender, EventArgs e)
        {
            if (textBox5!.Text.Length == 4)       //判断加密密钥长度是否正确
            {
                try
                {
                    textBox6!.Text =              //调用ToDecrypt方法得到解密后的字符串
                        Encrypt.ToDecrypt(textBox5.Text, textBox4!.Text);
                }
                catch (Exception ex)              //捕获异常
                {
                    MessageBox.Show(ex.Message);  //输出异常信息
                }
            }
            else
            {
                MessageBox.Show("密钥长度不符!", "提示");//提示用户输入密钥长度不正确
            }
        }
    }
}

2.类库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);//将密钥字符串转换为字节序列
                byte[] byte_data = Encoding.Unicode.GetBytes(str);      //将字符串转换为字节序列     
                using var des = DES.Create();                           //创建加密流对象                                                
                using var memory_stream = new MemoryStream();           //创建内存流对象
                using var crypto_stream = new CryptoStream(memory_stream, des.
                    CreateEncryptor(byte_key, byte_key), CryptoStreamMode.Write); //创建加密流对象
                crypto_stream.Write(byte_data, 0, byte_data.Length);    //向加密流中写入字节序列
                crypto_stream.FlushFinalBlock();                        //将数据压入基础流                                            
                crypto_stream.Close();                                  //关闭加密流                                                         
                memory_stream.Close();                                  //关闭内存流                                                     
                return Convert.ToBase64String(memory_stream.ToArray()); //从内存流中获取并返回加密后的字符串
            }
            catch (CryptographicException ce)
            {
                throw new Exception(ce.Message);
            }
        }

        internal static string ToDecrypt(string encryptKey, string str)
        {
            try
            {
                byte[] byte_key = Encoding.Unicode.GetBytes(encryptKey); //将密钥字符串转换为字节序列                  
                byte[] byte_data = Convert.FromBase64String(str);        //将加密后的字符串转换为字节序列                                  
                using var des = DES.Create();                            //创建加密流对象                                                                  
                using var memory_stream = new MemoryStream(byte_data);   //创建内存流对象并写入数据                  
                using var crypto_stream = new CryptoStream(memory_stream, des.
                    CreateDecryptor(byte_key, byte_key), CryptoStreamMode.Read);//创建加密流对象        
                byte[] bt_temp = new byte[200];             //创建字节序列对象                                                             
                MemoryStream memory_stream_temp = new();    //创建内存流对象                                     
                int i = 0;                                  //创建记数器                                                                                                 
                while ((i = crypto_stream.Read(bt_temp, 0, bt_temp.Length)) > 0)//使用while循环得到解密数据           
                {
                    memory_stream_temp.Write(bt_temp, 0, i);//将解密后的数据放入内存流                                        
                }
                crypto_stream.Close();                       //关闭加密流                                                                           
                memory_stream.Close();                       //关闭内存流                                                                       
                return Encoding.Unicode.GetString(memory_stream_temp.ToArray());//方法返回解密后的字符串
            }
            catch (CryptographicException ce)
            {
                throw new Exception(ce.Message);
            }
        }
    }
}

3.生成效果 

到此这篇关于C#使用CryptoStream类加密和解密字符串的实现的文章就介绍到这了,更多相关C# CryptoStream加密解密字符串内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文