· 4 years ago · Jun 22, 2021, 02:24 PM
1using System;
2
3public class CaesarCipher
4{
5 //символы русской азбуки
6 const string alfabet = "АБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ";
7
8 private string CodeEncode(string text, int k)
9 {
10 //добавляем в алфавит маленькие буквы
11 var fullAlfabet = alfabet + alfabet.ToLower();
12 var letterQty = fullAlfabet.Length;
13 var retVal = "";
14 for (int i = 0; i < text.Length; i++)
15 {
16 var c = text[i];
17 var index = fullAlfabet.IndexOf(c);
18 if (index < 0)
19 {
20 //если символ не найден, то добавляем его в неизменном виде
21 retVal += c.ToString();
22 }
23 else
24 {
25 var codeIndex = (letterQty + index + k) % letterQty;
26 retVal += fullAlfabet[codeIndex];
27 }
28 }
29
30 return retVal;
31 }
32
33 //шифрование текста
34 public string Encrypt(string plainMessage, int key)
35 => CodeEncode(plainMessage, key);
36
37 //дешифрование текста
38 public string Decrypt(string encryptedMessage, int key)
39 => CodeEncode(encryptedMessage, -key);
40}
41
42class Program
43{
44 static void Main(string[] args)
45 {
46 var cipher = new CaesarCipher();
47 Console.Write("Введите текст: ");
48 var message = Console.ReadLine();
49 Console.Write("Введите ключ: ");
50 var secretKey = Convert.ToInt32(Console.ReadLine());
51 var encryptedText = cipher.Encrypt(message, secretKey);
52 Console.WriteLine("Зашифрованное сообщение: {0}", encryptedText);
53 Console.WriteLine("Расшифрованное сообщение: {0}", cipher.Decrypt(encryptedText, secretKey));
54 Console.ReadLine();
55 }
56}
57