本文實例講述了C#實現(xiàn)簡單的3DES加密解密功能。分享給大家供大家參考,具體如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
|
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; using System.Security.Cryptography; using System.IO; namespace _3DES { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void CrypeBtn_Click( object sender, EventArgs e) { //實例化三倍DES服務提供者類 TripleDESCryptoServiceProvider TDES = new TripleDESCryptoServiceProvider(); //隨機生成密鑰和IV向量 TDES.GenerateIV(); TDES.GenerateKey(); //執(zhí)行加密 byte [] EncrypeByte = EncrypText(StrBox.Text, TDES.Key, TDES.IV); //顯示密文和密鑰 KeyBox.Text = Encoding.ASCII.GetString(TDES.Key); IVBox.Text = Encoding.ASCII.GetString(TDES.IV); CrypeBox.Text = Encoding.UTF8.GetString(EncrypeByte); //執(zhí)行解密 Str2Box.Text = DecrypText(EncrypeByte, TDES.Key, TDES.IV); } #region 加密 /// <summary> /// 執(zhí)行三倍DES加密的方法 /// </summary> /// <param name="Str">明文字符串</param> /// <param name="Key">密鑰</param> /// <param name="IV">IV向量</param> /// <returns>密文的字節(jié)序列</returns> private byte [] EncrypText( string Str, byte [] Key, byte [] IV) { //創(chuàng)建一個內(nèi)存流,用于存放密文 MemoryStream MS = new MemoryStream(); //創(chuàng)建一個三倍DES服務提供者對象 TripleDESCryptoServiceProvider TDES = new TripleDESCryptoServiceProvider(); //創(chuàng)建一個加密流,用于加密操作 CryptoStream CS = new CryptoStream(MS, TDES.CreateEncryptor(Key, IV), CryptoStreamMode.Write); //定義輸入,執(zhí)行加密操作 CS.Write(Encoding.UTF8.GetBytes(Str), 0, Str.Length); CS.FlushFinalBlock(); //返回將密文的內(nèi)存流轉(zhuǎn)換為字節(jié)序列并返回 return MS.ToArray(); } #endregion #region 解密 /// <summary> /// 執(zhí)行三倍DES解密的方法 /// </summary> /// <param name="CrypeText">密文的字節(jié)序列</param> /// <param name="Key">密鑰</param> /// <param name="IV">IV向量</param> /// <returns>明文的字符串</returns> private string DecrypText( byte [] CrypeText, byte [] Key, byte [] IV) { //創(chuàng)建一個內(nèi)存流,用于存放密文 MemoryStream MS = new MemoryStream(CrypeText); //創(chuàng)建一個三倍DES服務提供者對象 TripleDESCryptoServiceProvider TDES = new TripleDESCryptoServiceProvider(); //創(chuàng)建解密流 CryptoStream CS = new CryptoStream(MS, TDES.CreateDecryptor(Key, IV), CryptoStreamMode.Read); //創(chuàng)建一個用于存放明文的容器(字節(jié)序列) byte [] DecrypeBytes = new byte [CrypeText.Length]; //執(zhí)行解密 CS.Read(DecrypeBytes, 0, CrypeText.Length); //返回解密后的明文字符串 return Encoding.UTF8.GetString(DecrypeBytes); } #endregion } } |
運行效果:
希望本文所述對大家C#程序設(shè)計有所幫助。
原文鏈接:http://blog.csdn.net/microzone/article/details/16904531