fork(3) download
  1. using System;
  2. using System.Text;
  3. using System.Linq;
  4.  
  5. namespace Program {
  6. class Gaderypoluki {
  7. public class KeyIncorrectException : Exception {
  8. public string IncorrectionCause { get; private set; }
  9. public KeyIncorrectException(string cause) {
  10. this.IncorrectionCause = cause;
  11. }
  12. }
  13.  
  14. public static string Encrypt(string plain, string key) {
  15. if (key.Length % 2 == 0) {
  16. if (key.Length == key.Distinct().Count()) {
  17. var encrypted = new StringBuilder(plain);
  18. for (int i = 0; i < plain.Length; ++i)
  19. for (int j = 1; j < key.Length; j += 2)
  20. if (key[j] == plain[i]) encrypted[i] = key[j - 1];
  21. else if (key[j - 1] == plain[i]) encrypted[i] = key[j];
  22. return encrypted.ToString();
  23. }
  24. else throw new KeyIncorrectException("Characters in key must be unique!");
  25. }
  26. else throw new KeyIncorrectException("Incorrect key length! Key length must be even.");
  27. }
  28.  
  29. public static string Decrypt(string encrypted, string key) {
  30. return Encrypt(encrypted, key);
  31. }
  32. }
  33.  
  34. class Program {
  35. public static void Main(string[] args) {
  36. try {
  37. var plain = "Hello World";
  38. var key = "gaderypoluki";
  39. var encrypted = Gaderypoluki.Encrypt(plain, key);
  40. var decrypted = Gaderypoluki.Decrypt(encrypted, key);
  41. Console.WriteLine(encrypted);
  42. Console.WriteLine(decrypted);
  43. }
  44. catch(Gaderypoluki.KeyIncorrectException ex) {
  45. Console.WriteLine(ex.IncorrectionCause);
  46. }
  47. }
  48. }
  49. }
  50.  
Success #stdin #stdout 0.05s 24120KB
stdin
Standard input is empty
stdout
Hduup Wpyue
Hello World