i have written a program on mono-alphabetic ciphers , my code is running perfect for encryption but it give me wrong values when i am doing decryption. here is my code
using System;
class SubstitutionCipher
{
static void Main()
{
string key = "zyxwvutsrqponmlkjihgfedcba";
string plainText = "the quick brown fox jumps over the lazy dog";
string cipherText = Encrypt(plainText, key);
string decryptedText = Decrypt(cipherText, key);
Console.WriteLine("Plain : {0}", plainText);
Console.WriteLine("Encrypted : {0}", cipherText);
Console.WriteLine("Decrypted : {0}", decryptedText);
Console.ReadKey();
}
static string Encrypt(string plainText, string key)
{
char[] chars = new char[plainText.Length];
for (int i = 0; i < plainText.Length; i++)
{
if (plainText[i] == ' ')
{
chars[i] = ' ';
}
else
{
int j = plainText[i] - 97;
chars[i] = key[j];
}
}
return new string(chars);
}
public string reverse(string cipherText)
{
char[] charArray = cipherText.ToCharArray();
Array.Reverse(charArray);
return new string(charArray);
}
static string Decrypt(string cipherText, string key)
{
char[] chars = new char[cipherText.Length];
for (int i = 0; i < cipherText.Length; i++)
{
if (cipherText[i] == ' ')
{
chars[i] = ' ';
}
else
{
int j = key.IndexOf(cipherText[i]) - 97;
chars[i] = (char)j;
}
}
return new string(chars);
}
}
If key= zyxwvutsrqponmlkjihgfedcba
Outputs:
Plain : the quick brown fox jumps over the lazy dog
Encrypted : wyo xevks flnqa tnu hecdr nbol wyo pjzi gnm
Decrypted : ???????????????????????????????????????????
its decryption not working
Replace the line in Decrypt function:
int j = key.IndexOf(cipherText[i]) - 97;
with
int j= key.IndexOf(cipherText[i]) + 97;