Caesar Cipher Source Code - Part I

The Caesar cipher is one of the earliest known and simplest ciphers; Created and used in 44 BC by Julius Caesar. It is a type of substitution cipher in which each letter in the plain text is 'shifted' with certain number of places in the alphabet.
For example, if we right shift the alphabets by 3 char then we get the below text;






So now if we encrypt the message with above "TEST MESSAGE" will show below result







The encryption can be represented Mathematical, by first transforming the letters into numbers, like  A = 0, B = 1,…, Z = 25. To represent the Caesar Cipher encryption function, e(x), where x is the character we are encrypting, as:

E(X) = (X+K)  (mod 26)

 Where K represents key used to shift the letters in alphabets. for decryption we can use below equation 

E(X) = (X-K)  (mod 26)


I have written the below code which accept user input and right shift the alphabets by 9 char:


using System;
using System.Linq;
using System.Text;
namespace SecureHashingProject
{
public class CaesarCipher
{
private const string Letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
static void Main()
{
const int rightShiftKey = 9;
var result = new StringBuilder();
var message = Console.ReadLine();
if (string.IsNullOrEmpty(message))
{
Console.WriteLine("No data to encrypt");
return;
}
var lettersLength = Letters.Length;
foreach (var m in message.ToUpper())
{
if (Letters.Contains(m))
{
var num = Letters.IndexOf(m);
num += rightShiftKey;
if (num >= lettersLength)
num = num - lettersLength;
result = result.Append(Letters[num]);
}
else
{
result = result.Append(m);
}
}
Console.WriteLine($"Result: {result}");
Console.ReadLine();
}
}
}
view raw CaesarCipher.cs hosted with ❤ by GitHub

Result produce by of above code:



Comments

Popular posts from this blog

SHA-256(Source Code in C# using .Net in-built Cryptography library) - Part II

Basic of Cryptography (Type of Cryptography)- Part II