CCCPaste

5c3b9c8bb5926

namespace Messages
{
public class InvalidPasswordException : System.Exception
{
public string EncryptedText { get; }
public string Password { get; }

public InvalidPasswordException() { }
public InvalidPasswordException(string message) : base(message) { }
public InvalidPasswordException(string message, string encryptedText, string password) : base(message)
{
EncryptedText = encryptedText;
Password = password;
}
}

public class Rot13Encryption : IEncryption
{
public string Encrypt(string text)
{
if (text == null) return null;
var chars = new char[text.Length];
for (int i = 0; i < text.Length; i++) chars[i] = Rot13(text[i]);
return new string(chars);
}

public string Decrypt(string text)
{
if (text == null) return null;
var chars = new char[text.Length];
for (int i = 0; i < text.Length; i++) chars[i] = Rot13(text[i]);
return new string(chars);
}

public char GetMark() => 'R';

private char Rot13(char letter)
{
if (letter >= 'A' && letter <= 'Z')
letter = (char)('A' + (letter - 'A' + 13) % 26);
else if (letter >= 'a' && letter <= 'z')
letter = (char)('a' + (letter - 'a' + 13) % 26);
return letter;
}
}

public class PasswordBasedEncryption : IEncryption
{
private readonly string _password;

public PasswordBasedEncryption(string password)
{
if (string.IsNullOrEmpty(password))
throw new InvalidPasswordException();
_password = password;
}

public string Encrypt(string text)
{
if (text == null) return null;
var chars = new char[text.Length];
for (int i = 0; i < text.Length; i++)
{
int a = text[i];
int b = _password[i % _password.Length];
chars[i] = (char)(a + b);
}
return new string(chars);
}

public string Decrypt(string text)
{
if (text == null) return null;
var chars = new char[text.Length];
for (int i = 0; i < text.Length; i++)
{
int a = text[i];
int b = _password[i % _password.Length];
int c = a - b;
if (c < 0)
throw new InvalidPasswordException("Invalid password for decryption.", text, _password);
chars[i] = (char)c;
}
return new string(chars);
}

public char GetMark() => 'P';
}
}