CShap Vigenere加解密文本 源代码
时间: 2023-09-08 13:08:13 浏览: 44
以下是使用C#语言实现Vigenere加解密文本的源代码。
```csharp
using System;
public class VigenereCipher
{
private string key;
public VigenereCipher(string key)
{
this.key = key;
}
public string Encrypt(string plaintext)
{
string ciphertext = "";
int keyIndex = 0;
foreach (char c in plaintext)
{
int shift = key[keyIndex] - 'a';
char encryptedChar = (char)(((c + shift - 'a') % 26) + 'a');
ciphertext += encryptedChar;
keyIndex = (keyIndex + 1) % key.Length;
}
return ciphertext;
}
public string Decrypt(string ciphertext)
{
string plaintext = "";
int keyIndex = 0;
foreach (char c in ciphertext)
{
int shift = key[keyIndex] - 'a';
char decryptedChar = (char)((((c - shift - 'a') + 26) % 26) + 'a');
plaintext += decryptedChar;
keyIndex = (keyIndex + 1) % key.Length;
}
return plaintext;
}
}
class Program
{
static void Main(string[] args)
{
// Create a Vigenere cipher with key "secret"
VigenereCipher cipher = new VigenereCipher("secret");
// Encrypt and decrypt a message
string plaintext = "hello world";
string ciphertext = cipher.Encrypt(plaintext);
string decryptedText = cipher.Decrypt(ciphertext);
Console.WriteLine("Plaintext: " + plaintext);
Console.WriteLine("Ciphertext: " + ciphertext);
Console.WriteLine("Decrypted text: " + decryptedText);
}
}
```
该代码使用Vigenere密码算法加密和解密文本。在构造函数中,传递一个密钥字符串。然后,使用Encrypt方法加密明文字符串并返回密文字符串。使用Decrypt方法解密密文字符串并返回明文字符串。在Main方法中,首先创建一个VigenereCipher对象,并使用“secret”作为密钥字符串。然后,使用Encrypt方法加密“hello world”字符串,并使用Decrypt方法解密该字符串,最后将三个字符串打印到控制台。