生成C#的维吉尼亚加密和解密代码
时间: 2023-09-20 09:12:12 浏览: 40
好的,以下是C#的维吉尼亚加密和解密代码,您可以根据需要进行修改和使用:
```csharp
using System;
namespace VigenereCipher
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("请选择操作:\n1. 加密\n2. 解密");
int choice = int.Parse(Console.ReadLine());
Console.WriteLine("请输入明文/密文:");
string text = Console.ReadLine();
Console.WriteLine("请输入密钥:");
string key = Console.ReadLine();
if (choice == 1)
{
string cipherText = Encrypt(text, key);
Console.WriteLine("加密后的结果为:" + cipherText);
}
else if (choice == 2)
{
string plainText = Decrypt(text, key);
Console.WriteLine("解密后的结果为:" + plainText);
}
else
{
Console.WriteLine("输入错误!");
}
}
static string Encrypt(string text, string key)
{
string cipherText = "";
int keyIndex = 0;
for (int i = 0; i < text.Length; i++)
{
char c = text[i];
int offset = key[keyIndex] - 'A';
char encryptedChar = (char)((c + offset) % 256);
cipherText += encryptedChar;
keyIndex = (keyIndex + 1) % key.Length;
}
return cipherText;
}
static string Decrypt(string text, string key)
{
string plainText = "";
int keyIndex = 0;
for (int i = 0; i < text.Length; i++)
{
char c = text[i];
int offset = key[keyIndex] - 'A';
char decryptedChar = (char)((c - offset + 256) % 256);
plainText += decryptedChar;
keyIndex = (keyIndex + 1) % key.Length;
}
return plainText;
}
}
}
```
以上代码实现了维吉尼亚加密和解密的功能,并添加了简单的菜单选项,您可以根据需要进行修改和使用。