Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- namespace SpecialOlympics
- {
- class Program
- {
- interface IEncoder<T>
- {
- T Encode(T chipher, T key);
- }
- interface IDecoder<T>
- {
- T Decode(T text, T key);
- }
- class OneTimePad : IEncoder<char>, IDecoder<char>, IEncoder<string>, IDecoder<string>
- {
- private static readonly int LENGTH_OF_LATIN = 26;
- private string XorStrings(string text, string key, Func<char,char,char> operation)
- {
- if(text.Count(c => 'A' <= c && c <= 'Z') > key.Length) throw new ArgumentException("Key length should be greater then letters count in text");
- var builder = new StringBuilder(text);
- var numberOfLetters = 0;
- for (var i = 0; i < builder.Length; i++)
- {
- var c = builder[i];
- if ('A' <= c && c <= 'Z')
- {
- builder[i] = operation(c,key[numberOfLetters++]);
- }
- }
- return builder.ToString();
- }
- public string Encode(string chipher, string key)
- {
- return XorStrings(chipher, key, Encode);
- }
- public string Decode(string text, string key)
- {
- return XorStrings(text, key, Decode);
- }
- public char Encode(char chipher, char key)
- {
- return (char)('A' + (((chipher - 'A') + (key - 'A')) % LENGTH_OF_LATIN));
- }
- public char Decode(char text, char key)
- {
- var diff = (text - 'A') - (key - 'A');
- return (char)('A' + ((diff < 0 ? LENGTH_OF_LATIN + diff : diff) % LENGTH_OF_LATIN));
- }
- }
- static void Main(string[] args)
- {
- var oneTimePad = new OneTimePad();
- if (args.Length < 3)
- {
- Console.WriteLine("Not enought arguments");
- Console.WriteLine("First argument is action (--encode or --decode), second is key and third is text or chipher text.");
- }
- try
- {
- switch (args[0])
- {
- case "--encode":
- case "-e":
- Console.WriteLine(oneTimePad.Encode(args[2], args[1]));
- break;
- case "--decode":
- case "-d":
- Console.WriteLine(oneTimePad.Decode(args[2], args[1]));
- break;
- default:
- Console.WriteLine(
- "First argument is action (--encode or --decode), second is key and third is text or chipher text. Only latin upper case letters are encoded");
- break;
- }
- }
- catch (Exception e)
- {
- Console.WriteLine("Error occured: {0}",e.Message);
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment