Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //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.
- using System;
- using System.Text;
- class StringEncoding
- {
- static string EncodeString(string str, string key)
- {
- var result = new StringBuilder();
- int index = 0;
- for (int i = 0; i < str.Length; i++)
- {
- result.Append((char)(str[i] ^ key[index]));
- if (index + 1 < key.Length)
- {
- index++;
- }
- else
- {
- index = 0;
- }
- }
- return result.ToString();
- }
- static string DecodeString(string str, string key)
- {
- return EncodeString(str, key);
- }
- static void Main()
- {
- Console.Write("Enter a text: ");
- string text = Console.ReadLine();
- Console.Write("Enter a chiper: ");
- string cipher = Console.ReadLine();
- string encText = EncodeString(text, cipher);
- Console.WriteLine("After encoding: " + encText);
- string decText = DecodeString(encText, cipher); //Decoding is the same as encoding because if a^b = c --> a = c^b
- Console.WriteLine("After decoding: " + decText);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement