Hi guys
i was trying to integrate a very basic Client/Server chat software with Caesar Cipher. i just wanted to encrypt the communication using Caesar cipher. the Client/server chat software is using TCP sockets.i tried and integrated the cipher on client side but it encrypted all texts and its not readible and in english anymore. i just want to encrypt/decrypt the messages in the background.
**Server Code
**
snapshot
Click Here
http://www.geekpedia.com/Pictures/ChatClientAndServer/ChatClientsLive.png
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.Net;
using System.Net.Sockets;
using System.IO;
namespace ChatServer
{
public partial class Form1 : Form
{
private delegate void UpdateStatusCallback(string strMessage);
public Form1()
{
InitializeComponent();
}
private void btnListen_Click(object sender, EventArgs e)
{
// Parse the server's IP address out of the TextBox
IPAddress ipAddr = IPAddress.Parse(txtIp.Text);
// Create a new instance of the ChatServer object
ChatServer mainServer = new ChatServer(ipAddr);
// Hook the StatusChanged event handler to mainServer_StatusChanged
ChatServer.StatusChanged += new StatusChangedEventHandler(mainServer_StatusChanged);
// Start listening for connections
mainServer.StartListening();
// Show that we started to listen for connections
txtLog.AppendText("Monitoring for connections...\r\n");
}
public void mainServer_StatusChanged(object sender, StatusChangedEventArgs e)
{
// Call the method that updates the form
this.Invoke(new UpdateStatusCallback(this.UpdateStatus), new object[] { e.EventMessage });
}
private void UpdateStatus(string strMessage)
{
// Updates the log with the message
txtLog.AppendText(strMessage + "\r\n");
}
}
}
Client Code
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Threading;
namespace ChatClient
{
public partial class Form1 : Form
{
// Will hold the user name
private string UserName = "Unknown";
private StreamWriter swSender;
private StreamReader srReceiver;
private TcpClient tcpServer;
// Needed to update the form with messages from another thread
private delegate void UpdateLogCallback(string strMessage);
// Needed to set the form to a "disconnected" state from another thread
private delegate void CloseConnectionCallback(string strReason);
private Thread thrMessaging;
private IPAddress ipAddr;
private bool Connected;
public Form1()
{
// On application exit, don't forget to disconnect first
Application.ApplicationExit += new EventHandler(OnApplicationExit);
InitializeComponent();
}
// The event handler for application exit
public void OnApplicationExit(object sender, EventArgs e)
{
if (Connected == true)
{
// Closes the connections, streams, etc.
Connected = false;
swSender.Close();
srReceiver.Close();
tcpServer.Close();
}
}
private void btnConnect_Click(object sender, EventArgs e)
{
// If we are not currently connected but awaiting to connect
if (Connected == false)
{
// Initialize the connection
InitializeConnection();
}
else // We are connected, thus disconnect
{
CloseConnection("Disconnected at user's request.");
}
}
private void InitializeConnection()
{
// Parse the IP address from the TextBox into an IPAddress object
ipAddr = IPAddress.Parse(txtIp.Text);
// Start a new TCP connections to the chat server
tcpServer = new TcpClient();
tcpServer.Connect(ipAddr, 1986);
// Helps us track whether we're connected or not
Connected = true;
// Prepare the form
UserName = txtUser.Text;
// Disable and enable the appropriate fields
txtIp.Enabled = false;
txtUser.Enabled = false;
txtMessage.Enabled = true;
btnSend.Enabled = true;
btnConnect.Text = "Disconnect";
// Send the desired username to the server
swSender = new StreamWriter(tcpServer.GetStream());
swSender.WriteLine(txtUser.Text);
swSender.Flush();
// Start the thread for receiving messages and further communication
thrMessaging = new Thread(new ThreadStart(ReceiveMessages));
thrMessaging.Start();
}
private void ReceiveMessages()
{
// Receive the response from the server
srReceiver = new StreamReader(tcpServer.GetStream());
// If the first character of the response is 1, connection was successful
string ConResponse = srReceiver.ReadLine();
// If the first character is a 1, connection was successful
if (ConResponse[0] == '1')
{
// Update the form to tell it we are now connected
this.Invoke(new UpdateLogCallback(this.UpdateLog), new object[] { "Connected Successfully!" });
}
else // If the first character is not a 1 (probably a 0), the connection was unsuccessful
{
string Reason = "Not Connected: ";
// Extract the reason out of the response message. The reason starts at the 3rd character
Reason += ConResponse.Substring(2, ConResponse.Length - 2);
// Update the form with the reason why we couldn't connect
this.Invoke(new CloseConnectionCallback(this.CloseConnection), new object[] { Reason });
// Exit the method
return;
}
// While we are successfully connected, read incoming lines from the server
while (Connected)
{
// Show the messages in the log TextBox
this.Invoke(new UpdateLogCallback(this.UpdateLog), new object[] { srReceiver.ReadLine() });
}
}
// This method is called from a different thread in order to update the log TextBox
private void UpdateLog(string strMessage)
{
// Append text also scrolls the TextBox to the bottom each time
txtLog.AppendText(strMessage + "\r\n");
}
// Closes a current connection
private void CloseConnection(string Reason)
{
// Show the reason why the connection is ending
txtLog.AppendText(Reason + "\r\n");
// Enable and disable the appropriate controls on the form
txtIp.Enabled = true;
txtUser.Enabled = true;
txtMessage.Enabled = false;
btnSend.Enabled = false;
btnConnect.Text = "Connect";
// Close the objects
Connected = false;
swSender.Close();
srReceiver.Close();
tcpServer.Close();
}
// Sends the message typed in to the server
private void SendMessage()
{
if (txtMessage.Lines.Length >= 1)
{
swSender.WriteLine(txtMessage.Text);
swSender.Flush();
txtMessage.Lines = null;
}
txtMessage.Text = "";
}
// We want to send the message when the Send button is clicked
private void btnSend_Click(object sender, EventArgs e)
{
SendMessage();
}
// But we also want to send the message once Enter is pressed
private void txtMessage_KeyPress(object sender, KeyPressEventArgs e)
{
// If the key is Enter
if (e.KeyChar == (char)13)
{
SendMessage();
}
}
}
}
The Caeasar Cipher
Snapshot Click Here
Encryption
//Here I am only using characters A-Z(upper case)
//To increase the complexity of the ceaser cipher lower case"a-z", Numerics and Symbols also can be used
string alphabets = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
#region Encode
private void Encode_Click(object sender, EventArgs e)
{
string Text = richTextBox1.Text.ToUpper();
int key = Convert.ToInt32( comboBox1.Text);
string final = "";
int indexOfChar = 0;
char encryptedChar;
//Convert/encrypt each and every character of the text
foreach (char c in Text)
{
//Get the index of the character from alphabets variable
indexOfChar = alphabets.IndexOf(c);
if (c == ' ')//if encounters an white space
{
final = final + c;
}
else if(c == '\n')// if encounters a new line
{
final = final + c;
}
else if ((indexOfChar + key) > 25)//if the character is at the end of the string "alphabets"
{
//encrypt the character
encryptedChar = alphabets[(indexOfChar + key) - 26];
//add the encrypted character to a string every time to get an encrypted string
final = final + encryptedChar;
}
else
{
//encrypt the character
//add the encrypted character to a string every time to get an encrypted string
encryptedChar = alphabets[indexOfChar + key];
final = final + encryptedChar;
}
}
//Display encrypted text
richTextBox1.Clear();
richTextBox1.Text = final;
}
Decryption
string Text = richTextBox1.Text.ToUpper();
int key = Convert.ToInt32(comboBox1.Text);
string final = "";
int indexOfChar = 0;
char decryptedChar;
//Convert/decrypt each and every character of the text
foreach (char c in Text)
{
//Get the index of the character from alphabets variable
indexOfChar = alphabets.IndexOf(c);
if (c == ' ')//if encounters a white space
{
final = final + c;
}
else if (c == '\n')// if encounters a new line
{
final = final + c;
}
else if ((indexOfChar - key) < 0)//if the character is at the start of the string "alphabets"
{
//decrypt the character
//add the decrypted character to a string every time to get a decrypted string
decryptedChar = alphabets[(indexOfChar - key) + 26];
final = final + decryptedChar;
}
else
{
//decrypt the character
//add the decrypted character to a string every time to get a decrypted string
decryptedChar = alphabets[indexOfChar - key];
final = final + decryptedChar;
}
}
//Display decrypted text
richTextBox1.Clear();
richTextBox1.Text = final;
}
**this is how i integrated the encryption part to Client side
**
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Threading;
namespace ChatClient
{
public partial class Form1 : Form
{
// Will hold the user name
private string UserName = "Unknown";
private StreamWriter swSender;
private StreamReader srReceiver;
private TcpClient tcpServer;
// Needed to update the form with messages from another thread
private delegate void UpdateLogCallback(string strMessage);
// Needed to set the form to a "disconnected" state from another thread
private delegate void CloseConnectionCallback(string strReason);
private Thread thrMessaging;
private IPAddress ipAddr;
private bool Connected;
public Form1()
{
// On application exit, don't forget to disconnect first
Application.ApplicationExit += new EventHandler(OnApplicationExit);
InitializeComponent();
}
// The event handler for application exit
public void OnApplicationExit(object sender, EventArgs e)
{
if (Connected == true)
{
// Closes the connections, streams, etc.
Connected = false;
swSender.Close();
srReceiver.Close();
tcpServer.Close();
}
}
private void btnConnect_Click(object sender, EventArgs e)
{
// If we are not currently connected but awaiting to connect
if (Connected == false)
{
// Initialize the connection
InitializeConnection();
}
else // We are connected, thus disconnect
{
CloseConnection("Disconnected at user's request.");
}
}
private void InitializeConnection()
{
// Parse the IP address from the TextBox into an IPAddress object
ipAddr = IPAddress.Parse(txtIp.Text);
// Start a new TCP connections to the chat server
tcpServer = new TcpClient();
tcpServer.Connect(ipAddr, 1986);
// Helps us track whether we're connected or not
Connected = true;
// Prepare the form
UserName = txtUser.Text;
// Disable and enable the appropriate fields
txtIp.Enabled = false;
txtUser.Enabled = false;
txtMessage.Enabled = true;
btnSend.Enabled = true;
btnConnect.Text = "Disconnect";
// Send the desired username to the server
swSender = new StreamWriter(tcpServer.GetStream());
swSender.WriteLine(txtUser.Text);
swSender.Flush();
// Start the thread for receiving messages and further communication
thrMessaging = new Thread(new ThreadStart(ReceiveMessages));
thrMessaging.Start();
}
private void ReceiveMessages()
{
// Receive the response from the server
srReceiver = new StreamReader(tcpServer.GetStream());
// If the first character of the response is 1, connection was successful
string ConResponse = srReceiver.ReadLine();
// If the first character is a 1, connection was successful
if (ConResponse[0] == '1')
{
// Update the form to tell it we are now connected
this.Invoke(new UpdateLogCallback(this.UpdateLog), new object[] { "Connected Successfully!" });
}
else // If the first character is not a 1 (probably a 0), the connection was unsuccessful
{
string Reason = "Not Connected: ";
// Extract the reason out of the response message. The reason starts at the 3rd character
Reason += ConResponse.Substring(2, ConResponse.Length - 2);
// Update the form with the reason why we couldn't connect
this.Invoke(new CloseConnectionCallback(this.CloseConnection), new object[] { Reason });
// Exit the method
return;
}
// While we are successfully connected, read incoming lines from the server
while (Connected)
{
// Show the messages in the log TextBox
this.Invoke(new UpdateLogCallback(this.UpdateLog), new object[] { srReceiver.ReadLine() });
}
}
// This method is called from a different thread in order to update the log TextBox
private void UpdateLog(string strMessage)
{
string alphabets = "abcdefghijklmnopqrstuvwxyz";
string Text = strMessage;
int key = Convert.ToInt32(combokey.Text);
string final = "";
int indexOfChar = 0;
char decryptedChar;
//Convert/decrypt each and every character of the text
foreach (char c in Text)
{
//Get the index of the character from alphabets variable
indexOfChar = alphabets.IndexOf(c);
if (c == ' ')//if encounters a white space
{
final = final + c;
}
else if (c == '\n')// if encounters a new line
{
final = final + c;
}
else if ((indexOfChar - key) < 0)//if the character is at the start of the string "alphabets"
{
//decrypt the character
//add the decrypted character to a string every time to get a decrypted string
decryptedChar = alphabets[(indexOfChar - key) + 26];
final = final + decryptedChar;
}
else
{
//decrypt the character
//add the decrypted character to a string every time to get a decrypted string
decryptedChar = alphabets[indexOfChar - key];
final = final + decryptedChar;
}
}
//Display decrypted text
// richTextBox1.Clear();
// richTextBox1.Text = final;
// Append text also scrolls the TextBox to the bottom each time
txtLog.AppendText(final + "\r\n");
}
// Closes a current connection
private void CloseConnection(string Reason)
{
// Show the reason why the connection is ending
txtLog.AppendText(Reason + "\r\n");
// Enable and disable the appropriate controls on the form
txtIp.Enabled = true;
txtUser.Enabled = true;
txtMessage.Enabled = false;
btnSend.Enabled = false;
btnConnect.Text = "Connect";
// Close the objects
Connected = false;
swSender.Close();
srReceiver.Close();
tcpServer.Close();
}
// Sends the message typed in to the server
private void SendMessage()
{
if (txtMessage.Lines.Length >= 1)
{
string alphabets = "abcdefghijklmnopqrstuvwxyz";
string copy = txtMessage.Text;
txtenc.Text = copy;
string Text = txtenc.Text;
int key = Convert.ToInt32( combokey.Text);
string final = "";
int indexOfChar = 0;
char encryptedChar;
//Convert/encrypt each and every character of the text
foreach (char c in Text)
{
//Get the index of the character from alphabets variable
indexOfChar = alphabets.IndexOf(c);
if (c == ' ')//if encounters an white space
{
final = final + c;
}
else if(c == '\n')// if encounters a new line
{
final = final + c;
}
else if ((indexOfChar + key) > 25)//if the character is at the end of the string "alphabets"
{
//encrypt the character
encryptedChar = alphabets[(indexOfChar + key) - 26];
//add the encrypted character to a string every time to get an encrypted string
final = final + encryptedChar;
}
else
{
//encrypt the character
//add the encrypted character to a string every time to get an encrypted string
encryptedChar = alphabets[indexOfChar + key];
final = final + encryptedChar;
}
}
//Display encrypted text
txtenc.Clear();
txtenc.Text = final;
}
{
swSender.WriteLine(txtenc.Text);
swSender.Flush();
txtenc.Lines = null;
}
//txtenc.Text = "";
txtenc.Text = "";
}
// We want to send the message when the Send button is clicked
private void btnSend_Click(object sender, EventArgs e)
{
SendMessage();
}
// But we also want to send the message once Enter is pressed
private void txtMessage_KeyPress(object sender, KeyPressEventArgs e)
{
// If the key is Enter
if (e.KeyChar == (char)13)
{
SendMessage();
}
}
private void Form1_Load(object sender, EventArgs e)
{
}
}
}
be remided the Cipher code was taken from another software which is functioning.. i applied it to client side only and it worked but it encrypted everything in all text boxes therefore no user can understand a thing. please guide me on how can implement this cipher.. im a newbie in C#
thanks for you help =)