Sunday, 22 May 2011

Cryptography algorithm in C#.Net

  Substitution cypher:


using System;
using System.Text;
using System.IO;
using System.Net.Sockets;
class encriptclient
{
  public static void Main(string[] args)
 {
  string s1;
  string s2="";
  char[] c=new char[10];
  int a,b;
  string server=args[0];
  int port=Int32.Parse(args[1]);
  TcpClient client=null;
  NetworkStream netStream=null;

  try
 {
  client=new TcpClient(server,port);
  Console.WriteLine("Connected to server");
  netStream=client.GetStream();
  }
  catch(Exception e)
 {
  Console.WriteLine(e.Message);
  }

 for( ; ;)
 {
  Console.WriteLine("Enter the string");
  s1=Console.ReadLine();
  c=s1.ToCharArray();
  for(int i=0;i<s1.Length;i++)
  {
  a=(int)c[i];
  b=(a+2);
  if(b>122)
  b=b-26;
  c[i]=(char)(b);
  }
  for(int i=0;i<s1.Length;i++)
  s2=s2+c[i];
  Console.WriteLine("The encripted string is:{0}",s2);
  byte[] buffer=Encoding.ASCII.GetBytes(s2);
  netStream.Write(buffer,0,buffer.Length);
  byte[] buf=new byte[32];
  netStream.Read(buf,0,buf.Length);
  Console.WriteLine("The decripted string is:          {0}",Encoding.ASCII.GetString(buf,0,buf.Length));
 }
 netStream.Close();
 client.Close();
 }
}


Server side Decryption:

 using System;

 using System.Text;

 using System.Net;

 using System.Net.Sockets;

 class decriptserver

 {

   private const int size=32;

   public static void Main(string[] args)
  {
   char[] c=new char[10];
   int a,b;
   int port=Int32.Parse(args[0]);
   TcpListener listener=null;
   try
   {
    listener=new TcpListener(IPAddress.Any,port);
     listener.Start();
   }
   catch(Exception e)
  {
   Console.WriteLine(e.Message);
   }
  for(;;)
  {
  TcpClient client=null;
  NetworkStream netstream=null;
  client=listener.AcceptTcpClient();
  netstream=client.GetStream();
  Console.WriteLine("handling client");
byte[] buffer=new byte[size];
  netstream.Read(buffer,0,buffer.Length);
  Console.WriteLine("The string is{0}:",Encoding.ASCII.GetString(buffer,0,buffer.Length));
  string s1=Encoding.ASCII.GetString(buffer,0,buffer.Length);
  Console.WriteLine("the string is:{0}",s1);
  c=s1.ToCharArray();
 for(int i=0;c[i]!='\0';i++)
 {
 a=(int)c[i];
 b=(a-2);
 if(b<97)
 b=b+26;
 c[i]=(char)b;
 }
 string s2="";
 for(int i=0;i<s1.Length;i++)
 s2=s2+c[i];
 Console.WriteLine("The original text is:{0}",s2);
 byte[] buf=Encoding.ASCII.GetBytes(s2);
  netstream.Write(buf,0,buf.Length);
  netstream.Close();
  client.Close();
  }
 }



No comments:

Post a Comment