Thursday, February 24, 2011

Internet Control Message Protocol (ICMP)

Why ICMP is important

IP protocol lacks error reporting mechanism and hosting/managing queries. To compensate ICMP protocol comes to the role as a companion to IP protocol giving following two services.

  • Provides error reporting mechanism
  • Hosts and manages queries

Did you have any doubt

ICMP is a network layer protocol as IP is, so one would suspect whether ICMP messages are passed directly to the data link layer. The answer is no. ICMP messages are first encapsulated inside ip datagram and then passed to the below data link layer. Following image clearly shows you how it happens.


Talking about ICMP messages

  • Error reporting messages
  • ICMP acts as error reporting protocol it does not correct errors, error corrections are done by the higher level protocols. ICMP always sends the error messages to original source. There are five types of error messages as listed below.
    • Destination unreachable
    • Source quench
    • Time exeeded
    • Parameter problem
    • Redirection
  • Query messages
  • ICMP can also diagnose network problems through query messages. There are two pairs of query messages used for this purpose today.
    • Echo request or reply
    • Timestamp request or reply

Debugging tools that uses ICMP

ping

ping program can be used to find out whether a host is alive and responding. The source host sends an ICMP echo request message, if the destination host is alive it responds with ICMP echo reply messages.



traceroute

traceroute progam in unix or tracert in windows can be used to trace the route of a packet from source to destination.


Sunday, February 13, 2011

Crypto Samples in java part four -Stream Cipher

SendStream.java

import java.io.FileOutputStream;
import java.io.ObjectOutputStream;

import javax.crypto.Cipher;
import javax.crypto.CipherOutputStream;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;

public class SendStream {
 
 public static void main(String[] args) {
  
  String data = "This have I thought good to deliver thee rrrr";
  
  //---------------Encryption ---------------------------------

  SecretKey key = null;

  try {
   KeyGenerator keygen = KeyGenerator.getInstance("DES");
   key = keygen.generateKey();

   Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
   cipher.init(Cipher.ENCRYPT_MODE, key);
   
   FileOutputStream fos = new FileOutputStream("cipher.file"); 
   CipherOutputStream cos = new CipherOutputStream(fos, cipher);
   ObjectOutputStream oos = new ObjectOutputStream(cos);   
   
   
   oos.writeObject(data);
   oos.flush();
   oos.close();
   
   
   FileOutputStream fosKey = new FileOutputStream("key.file"); 
   ObjectOutputStream oosKey = new ObjectOutputStream(fosKey); 
   oosKey.writeObject(key);
   oosKey.writeObject(cipher.getIV());

  } catch (Exception e) {
   e.printStackTrace();
  } 

 }

}



ReceiveStream.java

package ucsc.cipher;

import java.io.FileInputStream;
import java.io.ObjectInputStream;

import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;

public class RecieveStream {
 
 public static void main(String[] args) {
  SecretKey key = null;

  try {
   FileInputStream fisKey = new FileInputStream("key.file"); 
   ObjectInputStream oosKey = new ObjectInputStream(fisKey); 
   
   key =  (SecretKey)oosKey.readObject();
   
   byte[] iv = (byte[])oosKey.readObject();


   Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
   cipher.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(iv));
   
   FileInputStream fis = new FileInputStream("cipher.file"); 
   CipherInputStream cis = new CipherInputStream(fis, cipher);
   ObjectInputStream ois = new ObjectInputStream(cis);   
   
   
            System.out.println((String)ois.readObject());   
   
  } catch (Exception e) {
   e.printStackTrace();
  } 

  
 }

}


Friday, February 11, 2011

Crypto Samples in java part three - Symmetric key encryption


A secret key is generated and only known by the sender and the receiver. Sender encrypts the plain text in to cypher text using the shared key and sends it to the receiver. After Receiver receives the encrypted message he/she decrypts the message using the shared key and grabs the original plain text (have a look at the image for a better understanding).

import java.security.spec.AlgorithmParameterSpec;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;

public class SimpleCipher {

 public static void main(String[] args) {

  String data = "This have I thought good to deliver thee";

  // ---------------Encryption ---------------------------------

  byte[] encrypted = null;
  byte[] iv = null;
  SecretKey key = null;

  try {
   KeyGenerator keygen = KeyGenerator.getInstance("DES");/*
                 * get the key
                 * generator
                 * instance
                 */
   key = keygen.generateKey();// generate the secret key

   Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
   /*
    * get cipher engine instance.DES algorithm is used and it requires
    * the input data to be 8-byte sized blocks. To encrypt a plain text
    * message that is not multiples of 8-byte blocks, the text message
    * must be padded with additional bytes to make the text message to
    * be multiples of 8-byte blocks.PKCS5Padding has used for that
    * purpose. note that CBC is a block cipher mode therefore we need
    * an initialization vector to chain blocks.
    */

   cipher.init(Cipher.ENCRYPT_MODE, key);/*
             * initializing cipher engine
             * for encryption
             */

   encrypted = cipher.doFinal(data.getBytes());/* do the encryption */

   iv = cipher.getIV();/*
         * save the initialization vector, remember that
         * we need this only when we are using cipher
         * block chaining mode for encryption
         */

  } catch (Exception e) {
   e.printStackTrace();
  }

  // ---------------Decryption ---------------------------------

  try {

   Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");/*
                   * get
                   * cipher
                   * engine
                   * instance
                   */

   AlgorithmParameterSpec param = new IvParameterSpec(iv);/*
                  * set the
                  * vector
                  * value
                  */

   cipher.init(Cipher.DECRYPT_MODE, key, param);/*
               * initializing cipher
               * engine for decryption
               */

   byte[] decrypted = cipher.doFinal(encrypted);/*
               * obtain original plain
               * text
               */

   System.out.println(new String(decrypted));

  } catch (Exception e) {
   e.printStackTrace();
  }

 }

}


Monday, January 31, 2011

Crypto Samples in java part two - Message Digest Streams

SendStream.java writes data along with message digest to a file "test".

SendStream.java

import java.io.*;
import java.security.*;

public class SendStream {
 public static void main(String args[]) {
  try {

   // We need to write data + message digest to this file.
   // Basically this is the file we need to send to the receiver
   FileOutputStream fos = new FileOutputStream("test");

   // We are going to calculate the message digest with SHA
   MessageDigest md = MessageDigest.getInstance("SHA");

   // Updates the associated message digest
   // using the bits going through the stream.
   DigestOutputStream dos = new DigestOutputStream(fos, md);

   ObjectOutputStream oos = new ObjectOutputStream(dos);

   String data = "This have I thought good to deliver thee, "
     + "that thou mightst not lose the dues of rejoicing "
     + "by being ignorant of what greatness is promised thee.";

   // Write the specified object to the ObjectOutputStream
   // Now the message being written to the FileOutputStream
   // Also - this will update the message digest of the written data as well..
   oos.writeObject(data);

   // urns the digest function on or off. The default is on. When it is on, a call to one
   // of the write methods results in an update on the message digest. But when it is off,
   // the message digest is not updated.
   dos.on(false);

   // Now let's also write the message digest to the file,
   oos.writeObject(md.digest());

  } catch (Exception e) {
   System.out.println(e);
  }
 }
}



RecieveStream.java takes file "test" as an input reads the data and calculate digest of that data and compare it with the original message digest read from the file "test".

RecieveStream.java

import java.io.FileInputStream;
import java.io.ObjectInputStream;
import java.security.DigestInputStream;
import java.security.MessageDigest;

public class RecieveStream {
 public static void main(String args[]) {
  try {

   // Here we get a file from the sender - and we need to verify it's message digest
   // The file contains both the message and the digest.
   FileInputStream fis = new FileInputStream("test");

   // We are going to calculate the message digest with SHA
   MessageDigest md = MessageDigest.getInstance("SHA");

   // Updates the associated message digest
   // using the bits going through the stream.
   DigestInputStream dis = new DigestInputStream(fis, md);

   ObjectInputStream oos = new ObjectInputStream(dis);

   // Read the message from the file
   String data = (String) oos.readObject();
   
   dis.on(false);

   // Original message digest from the input file.
   byte[] originalDigest = (byte[]) oos.readObject();

   if (MessageDigest.isEqual(originalDigest, dis.getMessageDigest().digest())) {
    System.out.println("VALID");
   } else {
    System.out.println("INVALID");
   }

  } catch (Exception e) {
   System.out.println(e);
  }
 }
}


Saturday, January 29, 2011

Crypto Samples in java part one - Message Digest

Here is a simple java program illustrating how to calculate a message digest and how to verify the message digest.

import java.security.MessageDigest;

public class SimpleHashing {
 public static void main(String args[]) {
  try {

   // ----------- Calculating digest ---------------------------

   // We are going to calculate the message digest with SHA
   MessageDigest md = MessageDigest.getInstance("SHA");

   String data = "This have I thought good to deliver thee, "
     + "that thou might not lose the dues of rejoicing "
     + "by being ignorant of what greatness is promised thee.";

   md.update(data.getBytes());
   byte[] digest = md.digest();

   // -----------Verifying Digest -----------------------------

   // We are going to calculate the message digest with SHA
   MessageDigest md2 = MessageDigest.getInstance("SHA");

   String data2 = "This have I thought good to deliver thee, "
     + "that thou might not lose the dues of rejoicing "
     + "by being ignorant of what greatness is promised thee.";

   md2.update(data2.getBytes());
   byte[] digestOriginal = digest;
   byte[] digestCalc = md2.digest();

   if (MessageDigest.isEqual(digestOriginal, digestCalc)) {
    System.out.println("VALID");
   } else {
    System.out.println("INVALID");
   }

  } catch (Exception e) {
   System.out.println(e);
  }
 }

}

Sunday, January 2, 2011

Synchronous Cilent Server application in java

Client code

Client.java

This program creates a socket connection with the server running on port 9050 on localhost and gets the input stream from the socket by chaining the BufferedReader with the InputStreamReader.


package clientserver;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
import java.net.UnknownHostException;

public class client {

 public static void main(String args[]) {

  try {
   Socket s = new Socket("127.0.0.1", 9050);

   InputStreamReader streamreader = new InputStreamReader(
     s.getInputStream());
   BufferedReader br = new BufferedReader(streamreader);

   String number = br.readLine();

   System.out.println("Today's number is " + number);
   br.close();

  } catch (UnknownHostException e) {
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  }

 }

}



Server code

Server.java

This program makes a ServerSocket and waits for client Requests. When a client tries to connect the server creates a new socket in a random port(using accept() method), which knows about the ip address and the port number of the client and makes the connection to the client. Also here server uses PrintWriter to sned messages to client.


package mainserver;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Random;

public class Server {

 public static void main(String args[]) {

  try {
   ServerSocket serverSock = new ServerSocket(9050);

   while (true) {

    Socket sock = serverSock.accept();
    PrintWriter pw = new PrintWriter(sock.getOutputStream());
    String TodayNum = new Server().getNumber();
    pw.println(TodayNum);
    pw.close();
    System.out.println(TodayNum);

   }

  } catch (IOException e) {
   e.printStackTrace();
  }

 }

 public String getNumber() {

  Random rg = new Random();
  int num = rg.nextInt(100);
  String numb = Integer.toString(num);
  return numb;

 }

}



Output

Saturday, January 1, 2011

Writing a C# client to an Axis2 service

Before moving into today's post content I would like to wish all the readers a happy new year 2011!

I am writing this post assuming you already have read my previous post subjected "Getting started with Apache Axis2". In there the client code has written in java, assume a situation where you need to write a client with C#, it is even simpler than writing a client in java.All you have to do is create a new project using microsoft visual studio and add the wsdl of your service(for the given example it is http://localhost:8080/axis2/services/mywebservice?wsdl) as service references and give a desired name for it(in following sample client code it is webserviceref), write the client code and run it



Client.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using webservice.clients.webserviceref;//name space of the service reference

namespace webservice.clients
{
    class Myclient
    {
        static void Main(string[] args)
        {

            webserviceref.mywebservicePortTypeClient cli = new mywebservicePortTypeClient("mywebserviceHttpSoap12Endpoint");
            Console.WriteLine(cli.sayHello("Hello"));
            Console.ReadLine();

        }
    }
}


Note that you have to start axis2 server before running the program.