1 using System;
2 using System.Collections.Generic;
3 using System.ComponentModel;
4 using System.Data;
5 using System.Drawing;
6 using System.Linq;
7 using System.Text;
8 using System.Windows.Forms;
9
10 namespace Vigenere
11 {
12 public partial class Form1 : Form
13 {
14 private string[,] matrix = new string[26, 26];
15 private ASCIIEncoding ascii = new ASCIIEncoding();
16
17 //key
18 private string key;
19 //code
20 private string code;
21 //text
22 private string text;
23
24 public Form1()
25 {
26 InitializeComponent();
27 #region Generate Virginia Martix
28 for (int i = 0; i < 26; i++)
29 {
30 for (int j = 0; j < 26; j++)
31 {
32 int number = 65 + i + j;
33 if (number > 90)
34 {
35 number -= 26;
36 }
37 byte[] bt = new byte[] { (byte)number };
38 matrix[i, j] = ascii.GetString(bt);
39 }
40 }
41 #endregion
42 }
43 //加密
44 private void button1_Click(object sender, EventArgs e)
45 {
46 key = this.txtKey.Text.ToString().ToUpper();
47 code = "";
48 text = this.txtText.Text.ToString().ToUpper();
49 List<int> keyNum = new List<int>(); ;
50
51 for (int i = 0; i < key.Length; i++)
52 {
53 string str = key.Substring(i, 1);
54 keyNum.Add((int)ascii.GetBytes(str)[0] - 65);
55 }
56
57 int index = -1;
58 for (int i = 0; i < this.text.Length; i++)
59 {
60 if (this.text.Substring(i, 1).ToString() == " ")
61 {
62 code += " ";
63 continue;
64 }
65 index++;
66 code += matrix[keyNum[index % key.Length], (int)ascii.GetBytes(this.text.Substring(i, 1))[0] - 65];
67 }
68
69 this.txtCode.Text = code.ToString();
70 }
71 //解密
72 private void button2_Click(object sender, EventArgs e)
73 {
74 key = this.txtKey.Text.ToString().ToUpper();
75 code = this.txtCode.Text.ToString().ToUpper();
76 text = "";
77 List<int> keyNum = new List<int>(); ;
78
79 for (int i = 0; i < key.Length; i++)
80 {
81 string str = key.Substring(i, 1);
82 keyNum.Add((int)ascii.GetBytes(str)[0] - 65);
83 }
84
85 int index = -1;
86 for (int i = 0; i < this.code.Length; i++)
87 {
88 if (this.code.Substring(i, 1).ToString() == " ")
89 {
90 text += " ";
91 continue;
92 }
93 index++;
94
95 for (int j = 0; j < 26; j++)
96 {
97 if (this.code.Substring(i, 1).ToString() == matrix[keyNum[index % key.Length], j])
98 {
99 byte[] bt = new byte[] { (byte)(j + 65) };
100 text += ascii.GetString(bt);
101 }
102 }
103 }
104
105 this.txtText.Text = text.ToString();
106 }
107 }
108 }
对于维吉尼亚方阵及运用维吉尼亚方阵的加密与解密,可参考http://baike.baidu.com/view/270838.htm?fromTaglist
画面结果如下: