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;
namespace Vigenere
{
public partial class Form1 : Form
{
private string[,] matrix = new string[26,26];
private ASCIIEncoding ascii = new ASCIIEncoding();
//key
private string key;
//code
private string code;
//text
private string text;
public Form1()
{
InitializeComponent();
#region Generate Virginia Martix
for (int i = 0; i < 26; i++)
{
for (int j = 0; j < 26; j++)
{
int number = 65 + i + j;
if (number > 90)
{
number -= 26;
}
byte[] bt = new byte[] { (byte)number };
matrix[i,j] = ascii.GetString(bt);
}
}
#endregion
}
//加密
private void button1_Click(object sender,EventArgs e)
{
key = this.txtKey.Text.ToString().toupper();
code = "";
text = this.txtText.Text.ToString().toupper();
List<int> keyNum = new List<int>(); ;
for (int i = 0; i < key.Length; i++)
{
string str = key.Substring(i,1);
keyNum.Add((int)ascii.GetBytes(str)[0] - 65);
}
int index = -1;
for (int i = 0; i < this.text.Length; i++)
{
if (this.text.Substring(i,1).ToString() == " ")
{
code += " ";
continue;
}
index++;
code += matrix[keyNum[index % key.Length],(int)ascii.GetBytes(this.text.Substring(i,1))[0] - 65];
}
this.txtCode.Text = code.ToString();
}
//解密
private void button2_Click(object sender,EventArgs e)
{
key = this.txtKey.Text.ToString().toupper();
code = this.txtCode.Text.ToString().toupper();
text = "";
List<int> keyNum = new List<int>(); ;
for (int i = 0; i < key.Length; i++)
{
string str = key.Substring(i,1);
keyNum.Add((int)ascii.GetBytes(str)[0] - 65);
}
int index = -1;
for (int i = 0; i < this.code.Length; i++)
{
if (this.code.Substring(i,1).ToString() == " ")
{
text += " ";
continue;
}
index++;
for (int j = 0; j < 26; j++)
{
if (this.code.Substring(i,1).ToString() == matrix[keyNum[index % key.Length],j])
{
byte[] bt = new byte[] { (byte)(j + 65) };
text += ascii.GetString(bt);
}
}
}
this.txtText.Text = text.ToString();
}
}
}
对于维吉尼亚方阵及运用维吉尼亚方阵的加密与解密,可参考维吉尼亚密码_百度百科
画面结果如下:
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。