Advertisement
Qrist

Vigenere cipher C#

Aug 14th, 2020
108
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.86 KB | None | 0 0
  1. using System;
  2.  
  3. namespace ConsoleApp10
  4. {
  5.     class Program
  6.     {
  7.         public static void Main()
  8.         {
  9.             char[] s = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' };
  10.             string key = "b";
  11.             for (int i = 0; i < s.Length; i++)
  12.             {
  13.                 VigenereEncrypt(s, key);
  14.                 Console.WriteLine(s);
  15.             }
  16.  
  17.             Console.WriteLine();
  18.  
  19.             for (int i = 0; i < s.Length; i++)
  20.             {
  21.                 VigenereDecrypt(s, key);
  22.                 Console.WriteLine(s);
  23.             }
  24.          
  25.         }
  26.  
  27.         static void VigenereEncrypt(char[] s, string key)
  28.         {
  29.             for (int i = 0; i < s.Length; i++) s[i] = Char.ToUpper(s[i]);
  30.             key = key.ToUpper();
  31.             int j = 0;
  32.             for (int i = 0; i < s.Length; i++)
  33.             {
  34.                 if (Char.IsLetter(s[i]))
  35.                 {
  36.                     s[i] = (char)(s[i] + key[j] - 'A');
  37.  
  38.                     if (s[i] > 'Z')
  39.                     {
  40.                         s[i] = (char)(s[i] - 'Z' + 'A' - 1);
  41.                     }
  42.                 }
  43.  
  44.                 j += 1 == key.Length ? 0 : j + 1;
  45.             }            
  46.         }
  47.  
  48.         static void VigenereDecrypt(char[] s, string key)
  49.         {
  50.             for (int i = 0; i < s.Length; i++)
  51.                 s[i] = Char.ToUpper(s[i]);
  52.                 key = key.ToUpper();
  53.             int j = 0;
  54.             for (int i = 0; i < s.Length; i++)
  55.             {
  56.                 if (Char.IsLetter(s[i]))
  57.                 {
  58.                     s[i] = s[i] >= key[j] ? (char)(s[i] - key[j] + 'A') : (char)('A' + ('Z' - key[j] + s[i] - 'A') + 1);
  59.                 }
  60.  
  61.                 j +=1 == key.Length ? 0 : j + 1;
  62.             }
  63.         }
  64.     }
  65. }
  66.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement