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);
}
}
}