Showing posts with label crypto. Show all posts
Showing posts with label crypto. Show all posts

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

}