Example: encrypption in C# console using mod of 26
namespace CaesarCipher
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Chose One: Encrypt / Decrypt");
string encryptDecrypt = Console.ReadLine();
string lowerEncryptDecrypt = encryptDecrypt.ToLower();
if (lowerEncryptDecrypt == "encrypt")
{
Console.WriteLine("Enter a message to encrypt.");
string unencryptedMessage = Console.ReadLine();
string lowerUnencryptedMessage = unencryptedMessage.ToLower();
Console.WriteLine("Enter a value for the cipher.");
int cipherValue = Int16.Parse(Console.ReadLine());
char[] secretMessage = lowerUnencryptedMessage.ToCharArray();
Console.WriteLine(Encrypt(secretMessage, cipherValue));
} else if (lowerEncryptDecrypt == "decrypt")
{
Console.WriteLine("Enter a message to decrypt.");
string msgToDecrypt = Console.ReadLine();
string lowerMsgToDecrypt = msgToDecrypt.ToLower();
Console.WriteLine("Enter a value for the cipher.");
int cipherValue = Int16.Parse(Console.ReadLine());
char[] secretMessage = lowerMsgToDecrypt.ToCharArray();
Console.WriteLine(Decrypt(secretMessage, cipherValue));
} else
{
Console.WriteLine("That is not a valid choice. Please restart.");
}
}
static string Encrypt(char[] secretMessage, int cipherValue)
{
char[] alphabet = new char[] {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'};
char[] encryptedMessage = new char[secretMessage.Length];
for (int i = 0; i < secretMessage.Length; i++)
{
char unencryptedLetter = secretMessage[i];
if (Char.IsLetter(unencryptedLetter) == true)
{
int unencryptedAlphabetPosition = Array.IndexOf(alphabet, unencryptedLetter);
int encryptedAlphabetPosition = (unencryptedAlphabetPosition + cipherValue) % 26;
char encryptedLetter = alphabet[encryptedAlphabetPosition];
encryptedMessage[i] = encryptedLetter;
} else {
encryptedMessage[i] = unencryptedLetter;
}
}
string encryptedMessageResult = string.Join("", encryptedMessage);
return encryptedMessageResult;
}
static string Decrypt(char[] secretMessage, int cipherValue)
{
char[] alphabet = new char[] {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'};
char[] encryptedMessage = new char[secretMessage.Length];
for (int i = 0; i < secretMessage.Length; i++)
{
char unencryptedLetter = secretMessage[i];
if (Char.IsLetter(unencryptedLetter) == true)
{
int unencryptedAlphabetPosition = Array.IndexOf(alphabet, unencryptedLetter);
int encryptedAlphabetPosition = (unencryptedAlphabetPosition + (26 - (cipherValue % 26))) % 26;
char encryptedLetter = alphabet[encryptedAlphabetPosition];
encryptedMessage[i] = encryptedLetter;
} else {
encryptedMessage[i] = unencryptedLetter;
}
}
string encryptedMessageResult = string.Join("", encryptedMessage);
return encryptedMessageResult;
}
}
}