随机练习:C#实现维吉尼亚加密与解密(解密前提为已知密匙)

时间:2023-03-09 08:15:03
随机练习:C#实现维吉尼亚加密与解密(解密前提为已知密匙)
 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[, ];
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 = ; i < ; i++)
{
for (int j = ; j < ; j++)
{
int number = + i + j;
if (number > )
{
number -= ;
}
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 = ; i < key.Length; i++)
{
string str = key.Substring(i, );
keyNum.Add((int)ascii.GetBytes(str)[] - );
} int index = -;
for (int i = ; i < this.text.Length; i++)
{
if (this.text.Substring(i, ).ToString() == " ")
{
code += " ";
continue;
}
index++;
code += matrix[keyNum[index % key.Length], (int)ascii.GetBytes(this.text.Substring(i, ))[] - ];
} 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 = ; i < key.Length; i++)
{
string str = key.Substring(i, );
keyNum.Add((int)ascii.GetBytes(str)[] - );
} int index = -;
for (int i = ; i < this.code.Length; i++)
{
if (this.code.Substring(i, ).ToString() == " ")
{
text += " ";
continue;
}
index++; for (int j = ; j < ; j++)
{
if (this.code.Substring(i, ).ToString() == matrix[keyNum[index % key.Length], j])
{
byte[] bt = new byte[] { (byte)(j + ) };
text += ascii.GetString(bt);
}
}
} this.txtText.Text = text.ToString();
}
}
} 对于维吉尼亚方阵及运用维吉尼亚方阵的加密与解密,可参考http://baike.baidu.com/view/270838.htm?fromTaglist 画面结果如下:

随机练习:C#实现维吉尼亚加密与解密(解密前提为已知密匙)


随机练习:C#实现维吉尼亚加密与解密(解密前提为已知密匙)