using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace StringEncryption
{
class Program
{
static void Main(string[] args)
{
// the message to encrypt
string messageStr = "Oh what a beautifull morning, oh what a beautifull day!";
// the secret key used, can be anything make it at least 2 chars long
string keyStr = "ABCDEFG";
Console.WriteLine("Encrypted string:");
StringBuilder OutStr = StringEncrypt(messageStr, keyStr);
Console.WriteLine(OutStr.ToString());
Console.WriteLine("Deciphered string:");
StringBuilder OutStr2 = StringEncrypt(OutStr.ToString(), keyStr);
Console.WriteLine(OutStr2.ToString());
Console.ReadKey();
}
private static StringBuilder StringEncrypt(string messageStr, string keyStr)
{
const int EOS = -1; //end of string condition
StringReader Msr = new StringReader(messageStr);
StringBuilder OutStr = new StringBuilder();
// alternatively BinaryReader and BinaryWriter could be used here
int keyLength = keyStr.Length - 1;
int index = 0;
char ch;
int x;
do
{
x = Msr.Read() ^ keyStr[index]; //XOR
ch = Convert.ToChar(x);
OutStr.Append(ch);
index++;
if (index > keyLength) index = 0; //start all over with the key
} while (Msr.Peek() != EOS);
return OutStr;
}
}
}