using System;
using System.Text;
using System.Linq;
namespace Program {
class Gaderypoluki {
public class KeyIncorrectException : Exception {
public string IncorrectionCause { get; private set; }
public KeyIncorrectException(string cause) {
this.IncorrectionCause = cause;
}
}
public static string Encrypt(string plain, string key) {
if (key.Length % 2 == 0) {
if (key.Length == key.Distinct().Count()) {
var encrypted = new StringBuilder(plain);
for (int i = 0; i < plain.Length; ++i)
for (int j = 1; j < key.Length; j += 2)
if (key[j] == plain[i]) encrypted[i] = key[j - 1];
else if (key[j - 1] == plain[i]) encrypted[i] = key[j];
return encrypted.ToString();
}
else throw new KeyIncorrectException("Characters in key must be unique!");
}
else throw new KeyIncorrectException("Incorrect key length! Key length must be even.");
}
public static string Decrypt(string encrypted, string key) {
return Encrypt(encrypted, key);
}
}
class Program {
public static void Main(string[] args) {
try {
var plain = "Hello World";
var key = "gaderypoluki";
var encrypted = Gaderypoluki.Encrypt(plain, key);
var decrypted = Gaderypoluki.Decrypt(encrypted, key);
Console.WriteLine(encrypted);
Console.WriteLine(decrypted);
}
catch(Gaderypoluki.KeyIncorrectException ex) {
Console.WriteLine(ex.IncorrectionCause);
}
}
}
}