单字母替换加密方法——单表置换密码C#代码,给定的n位密钥替换字母表前n位(若有重复只记第一次),后面的按照字母表顺不重复的排列构成26位替换表,用户可选择加密解密,可自行输入密钥
时间: 2024-02-22 19:54:52 浏览: 14
以下是单表置换密码的C#实现代码,包括加密和解密函数:
```csharp
using System;
using System.Linq;
class MonoalphabeticSubstitution
{
static string Encrypt(string plainText, string key)
{
string alphabet = "abcdefghijklmnopqrstuvwxyz";
string table = key + new string(alphabet.Except(key).ToArray());
return new string(plainText.Select(c => char.IsLetter(c) ? table[alphabet.IndexOf(char.ToLower(c))] : c).ToArray());
}
static string Decrypt(string cipherText, string key)
{
string alphabet = "abcdefghijklmnopqrstuvwxyz";
string table = key + new string(alphabet.Except(key).ToArray());
return new string(cipherText.Select(c => char.IsLetter(c) ? alphabet[table.IndexOf(char.ToLower(c))] : c).ToArray());
}
static void Main()
{
Console.Write("Enter the key: ");
string key = Console.ReadLine().ToLower();
Console.Write("Enter the plain text: ");
string plainText = Console.ReadLine().ToLower();
string cipherText = Encrypt(plainText, key);
Console.WriteLine("Cipher text: " + cipherText);
string decryptedText = Decrypt(cipherText, key);
Console.WriteLine("Decrypted text: " + decryptedText);
}
}
```
在这个实现中,我们使用了LINQ库的Except()函数来确定替换表中剩余的字母。如果用户输入的密钥中包含重复字母,只会使用第一个出现的字母。