Advertisement
nina75

Strings/Task7

Jan 18th, 2014
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.51 KB | None | 0 0
  1. //Write a program that encodes and decodes a string using given encryption key (cipher). The key consists of a sequence of characters. The encoding/decoding is done by performing XOR (exclusive or) operation over the first letter of the string with the first of the key, the second – with the second, etc. When the last key character is reached, the next is the first.
  2.  
  3. using System;
  4. using System.Text;
  5.  
  6. class StringEncoding
  7. {
  8.     static string EncodeString(string str, string key)
  9.     {
  10.         var result = new StringBuilder();
  11.         int index = 0;
  12.         for (int i = 0; i < str.Length; i++)
  13.         {
  14.             result.Append((char)(str[i] ^ key[index]));
  15.             if (index + 1 < key.Length)
  16.             {
  17.                 index++;
  18.             }
  19.             else
  20.             {
  21.                 index = 0;
  22.             }
  23.         }
  24.  
  25.         return result.ToString();
  26.     }
  27.     static string DecodeString(string str, string key)
  28.     {
  29.         return EncodeString(str, key);
  30.     }
  31.    
  32.     static void Main()
  33.     {
  34.         Console.Write("Enter a text: ");
  35.         string text = Console.ReadLine();
  36.  
  37.         Console.Write("Enter a chiper: ");
  38.         string cipher = Console.ReadLine();
  39.  
  40.         string encText = EncodeString(text, cipher);
  41.         Console.WriteLine("After encoding: " + encText);
  42.  
  43.         string decText = DecodeString(encText, cipher); //Decoding is the same as encoding because if a^b = c --> a = c^b
  44.         Console.WriteLine("After decoding: " + decText);
  45.        
  46.     }
  47. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement