C#使用CryptoStream類加密和解密字符串的實現(xiàn)
在使用CryptoStream前要先引用命名空間using System.Security.Cryptography。
一、CrytoStream的加密方法
記住,不能再使用DESCryptoServiceProvider().CreateEncryptor()創(chuàng)建加密流,因為它已經(jīng)被微軟廢棄了。會提示“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); //將密鑰字符串轉(zhuǎn)換為字節(jié)序列
byte[] byte_data = Encoding.Unicode.GetBytes(str); //將字符串轉(zhuǎn)換為字節(jié)序列
using var des = DES.Create(); //創(chuàng)建加密流對象
using var memory_stream = new MemoryStream(); //創(chuàng)建內(nèi)存流對象
using var crypto_stream = new CryptoStream(memory_stream, des.
CreateEncryptor(byte_key, byte_key), CryptoStreamMode.Write); //創(chuàng)建加密流對象
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的解密方法
與加密方法具有相同的注意事項。
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)建加密流對象
using var memory_stream = new MemoryStream(byte_data); //創(chuàng)建內(nèi)存流對象并寫入數(shù)據(jù)
using var crypto_stream = new CryptoStream(memory_stream, des.
CreateDecryptor(byte_key, byte_key), CryptoStreamMode.Read); //創(chuàng)建加密流對象
byte[] bt_temp = new byte[200]; //創(chuàng)建字節(jié)序列對象
MemoryStream memory_stream_temp = new(); //創(chuàng)建內(nèi)存流對象
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);
}
}三、實例
對字符串加密、解密的實例,秘鑰=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) //判斷加密密鑰長度是否正確
{
try
{
textBox3!.Text = //調(diào)用實例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 = //調(diào)用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);//將密鑰字符串轉(zhuǎn)換為字節(jié)序列
byte[] byte_data = Encoding.Unicode.GetBytes(str); //將字符串轉(zhuǎn)換為字節(jié)序列
using var des = DES.Create(); //創(chuàng)建加密流對象
using var memory_stream = new MemoryStream(); //創(chuàng)建內(nèi)存流對象
using var crypto_stream = new CryptoStream(memory_stream, des.
CreateEncryptor(byte_key, byte_key), CryptoStreamMode.Write); //創(chuàng)建加密流對象
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)建加密流對象
using var memory_stream = new MemoryStream(byte_data); //創(chuàng)建內(nèi)存流對象并寫入數(shù)據(jù)
using var crypto_stream = new CryptoStream(memory_stream, des.
CreateDecryptor(byte_key, byte_key), CryptoStreamMode.Read);//創(chuàng)建加密流對象
byte[] bt_temp = new byte[200]; //創(chuàng)建字節(jié)序列對象
MemoryStream memory_stream_temp = new(); //創(chuàng)建內(nèi)存流對象
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類加密和解密字符串的實現(xiàn)的文章就介紹到這了,更多相關(guān)C# CryptoStream加密解密字符串內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
C#調(diào)用C類型dll入?yún)閟truct的問題詳解
這篇文章主要給大家介紹了關(guān)于C#調(diào)用C類型dll入?yún)閟truct問題的相關(guān)資料,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-03-03
常用.NET工具(包括.NET可再發(fā)行包2.0)下載
常用.NET工具(包括.NET可再發(fā)行包2.0)下載...2007-03-03
c# 連接access數(shù)據(jù)庫config配置
c# 連接access數(shù)據(jù)庫config配置,需要的朋友可以參考一下2013-02-02
c# WPF中通過雙擊編輯DataGrid中Cell的示例(附源碼)
這篇文章主要介紹了c# WPF中通過雙擊編輯DataGrid中Cell的示例(附源碼),幫助大家更好的理解和學(xué)習(xí)使用c#,感興趣的朋友可以了解下2021-03-03
一文搞懂C#實現(xiàn)讀寫文本文件中的數(shù)據(jù)
這篇文章重點給大家介紹C#實現(xiàn)讀寫文本文件中的數(shù)據(jù)的一些知識,讀取.txt文件數(shù)據(jù)的實例代碼及寫入讀取過程完整代碼,感興趣的朋友跟隨小編一起看看吧2021-06-06

