I have windows form application that encrypt the string and decrypt it back using Caesar Algorithm. When encrypting a string I have to remove spaces from it ,but when I'll decrypt it again I should bring back the removed spaces into their actual places.
The problem I faced in this case is in bringing the removed spaces from the encrypted string and also when decrypting there are some letters are changed into special characters like this pattern where the encryption key is 3:
Plain text: My name is Shafaq Zahir
Encrypted text: PbqdphlvVkdidtCdklu
Decrypted text: M_nameisShafaq@ahir
This is my code
class CaesarAlgorithm
{
public string Encrypt(string pt,int key)
{
char[] buffer = pt.Replace(" ",string.Empty).ToCharArray();
//char[] buffer = pt.ToCharArray();
for(int i=0;i<buffer.Length;i++)
{
if (buffer[i] >= 'a' && buffer[i] <= 'z')
{
buffer[i] = (char)(buffer[i] + key);
if (buffer[i] > 'z')
{
buffer[i] = (char)(buffer[i] - 26);
}
}
else if (buffer[i] >= 'A' && buffer[i] <= 'Z')
{
buffer[i] = (char)(buffer[i] + key);
if (buffer[i] > 'Z')
{
buffer[i] = (char)(buffer[i] - 26);
}
}
}
return new string (buffer);
}
public string Decrypt(string pt,int key)
{
char[] buffer = pt.ToCharArray();
for (int i = 0; i < buffer.Length; i++)
{
if (buffer[i] >= 'a' && buffer[i] <= 'z')
{
buffer[i] = (char)(buffer[i] - key);
if (buffer[i] > 'z')
{
buffer[i] = (char)(buffer[i] - 26);
}
}
else if (buffer[i] >= 'A' && buffer[i] <= 'Z')
{
buffer[i] = (char)(buffer[i] - key);
if (buffer[i] > 'Z')
{
buffer[i] = (char)(buffer[i] - 26);
}
}
}
return new string(buffer);
}
}
}
Shouldn't this code
if (buffer[i] > 'Z')
{
buffer[i] = (char)(buffer[i] - 26);
}
Be
if (buffer[i] <'A')
{
buffer[i] = (char)(buffer[i] + 26);
}
In your decrypt function? To check if it's less than A or a because you are subtracting key from it. Also don't replace spaces in your code. Just encrypt them and decrypt them they will stay, that said, there is no way to recover spaces unless you keep index information with it.!