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