Wednesday, January 30, 2013
Many of you must have seen that a MD5/SHA-1/SHA-256/SHA-512 hash is given for every file that you download from internet. This is necessary to check whether the file downloaded has the same hash as that of original file and there is no error while downloading. This is also used in case of copyrighted objects. You must have thought how can you generate this hash. Today I am going to describe how you can very easily generate hash of a file. Here I will use java.security.MessageDigest and java.security.DigestInputStream class.
MessageDigest class : A MessageDigest object starts out initialized with defined hash algorithm. The data is processed through it using the update methods. At any point reset can be called to reset the digest. Once all the data to be updated has been updated, one of the digest methods should be called to complete the hash computation. The digest method can be called once for a given number of updates. After digest has been called, the MessageDigest object is reset to its initialized state.
DigestInputStream class : A transparent stream that updates the associated message digest using the bits going through the stream. To complete the message digest computation, call one of the digest methods on the associated message digest after your calls to one of this digest input stream's read methods.
--------------------------------------------------------------------------------------------------------------------------
Java Source Code
--------------------------------------------------------------------------------------------------------------------------
import java.io.InputStream;
import java.io.IOException;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.DigestInputStream;
import java.security.NoSuchAlgorithmException;

public class HashFile {
    
    private String fname;
    private DigestInputStream dis;
    private MessageDigest md;
    
    public HashFile(String fname,String hashAlgo) {
     try{
        md=MessageDigest.getInstance(hashAlgo);  //initializing
        InputStream fis=getClass().getResourceAsStream(fname);
        dis=new DigestInputStream(fis,md);  //getting stream
     }catch(NoSuchAlgorithmException e){
      e.printStackTrace();
     }
    }
    
    public String generateHash()throws IOException{
     byte[] buf=new byte[4096];  //setting buffer
     while (dis.read()!=-1);  //reading and updating message digest
     byte[] output=md.digest();  //getting hash data in bytes
     BigInteger bi=new BigInteger(1,output);
     String hashText=bi.toString(16);  //getting hex value of hash
     dis.close();  //closing stream
     
     return hashText;
    }
    
    public static void main(String[] args) throws Exception{
     if(args.length<2){
       System.out.println("INVALID INPUT");
       System.exit(1);
     }
     HashFile obj=new HashFile(args[0],args[1]);
     System.out.println (obj.generateHash());  //printing hash
    }
}


NOTE ; Very soon I will be posting a GUI version of this. So stay connected.
--------------------------------------------------------------------------------------------------------------------------
Output
--------------------------------------------------------------------------------------------------------------------------
The input file contained text abcdefghi. The algorithm used here is Md5. To use any other algorithm, pass either SHA-1/SHA-256/SHA-512 as a command-line argument instead of Md5.
--------------------------------------------------------------------------------------------------------------------------
Download Links
--------------------------------------------------------------------------------------------------------------------------
DOWNLOAD the source from Mediafire
Monday, January 21, 2013
Today I am going to post a program that will use a text string as a clipping path and draw an image with it. As you know, Graphics2D can do a number of operations like transformations,clipping and alpha compositing. Here in our case, we will use images. First of all we will rotate the user space. This is just to give our output a more better look. The clipping shape is created in the method getClippingShape(Graphics) method. Here a text is chosen and a Font instance is created. This font is used to create GlyphVector for the clipping shape string. Then the shape is retrieved by calling getOutline() method of GlyphVector. The clip method of Graphics2D is called, followed by reading of the image from file using ImageIO's read method. Finally the image is drawn on panel and displayed.
Screenshots of original and final images
Origibal Image
Final Clip Image








--------------------------------------------------------------------------------------------------------------------------
Java Source Code
--------------------------------------------------------------------------------------------------------------------------

import java.awt.*; 
import java.awt.font.*; 
import java.awt.image.BufferedImage; 
import java.io.File;
import java.io.IOException;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.imageio.ImageIO; 

public class ClipImage extends JPanel{

   @Override
    public void paintComponent(Graphics g){
Graphics2D g2 = (Graphics2D)g;  //casting
        Dimension d = getSize();
        g2.rotate(-Math.PI / 12, d.width / 2, d.height / 2);  //rotating
        g2.clip(getClippingShape(g2));  //clipping
        try{
        //reading image from file
           final BufferedImage image = ImageIO.read(new File("image.jpg"));
           g2.drawImage(image, 0, 0, null);  //drawing image
        }catch(IOException e){
        e.printStackTrace();
        }
    }

    private Shape getClippingShape(Graphics2D g2) {
          String s = "Java 2D";  //defining clipping text
          Font font = new Font("Serif", Font.PLAIN, 122);  //text font
          FontRenderContext frc = g2.getFontRenderContext(); 
          GlyphVector gv = font.createGlyphVector(frc, s);  //text glyph
          Shape clippingShape = gv.getOutline(10, 120);  //getting clip shape
          return clippingShape; //returning shape
     }
     
     public static void main(String[] args){ 
        JFrame f=new JFrame("Clipping_Image");
        f.getContentPane().add(new ClipImage());
        f.setSize(430,220);
        f.setVisible(true);
        f.setDefaultCloseOperation(f.EXIT_ON_CLOSE);
     }
}
--------------------------------------------------------------------------------------------------------------------------
Download Links
--------------------------------------------------------------------------------------------------------------------------
DOWNLOAD the source from Mediafire
DOWNLOAD the source from 4shared
Sunday, January 13, 2013
Today I am going to post a program that will be able to compress any file in GZIP format. Java language can be used very efficiently for this purpose. There is a special package java.util.zip which contains several classes that can be used for compressing files and folders. Today I am going to deal with GZIPOutputStream . This particular class is used to produce with a file in compressed GZIP format with extension .gz . Here at first the file to be compressed is taken as input from user. Then FileInputStream is used to open a stream connecting to that file. Next the data from file is read in a buffer of capacity 4K. Then the buffer is written to the output stream. Here output stream is nothing but a FileOutputStream wrapped over with a GZIPOutputStream . This process of reading and writing goes on until end of file is reached.
--------------------------------------------------------------------------------------------------------------------------
Java Source Code
--------------------------------------------------------------------------------------------------------------------------

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.GZIPOutputStream;

public class CompressFile {
  public void gzipFile(String from, String to) throws IOException {
    FileInputStream in = new FileInputStream(from);  //stream to input file
    GZIPOutputStream out = new GZIPOutputStream(new FileOutputStream(to));  //stream to output file
    byte[] buffer = new byte[4096];  //defining buffer capacity
    int bytesRead;
    while ((bytesRead = in.read(buffer)) != -1)  //reading into buffer
      out.write(buffer, 0, bytesRead);  //writing buffer contents to output stream
    in.close();  //closing both streams
    out.close();
  }

  public static void main(String args[]) throws IOException {
  if(args.length>0){
        String from=args[0];  //getting source file as command line input
        new CompressFile().gzipFile(from,from+".gz");
  }
  }
}
NOTE : Very soon I will be posting a GUI version of this ptogram.
--------------------------------------------------------------------------------------------------------------------------
Download Links
--------------------------------------------------------------------------------------------------------------------------
DOWNLOAD the source from Mediafire
DOWNLOAD the source from 4shared
Wednesday, January 9, 2013
In my last post I have mentioned about working differences between hashing and encryption. Based on their working, today I am going to post when and where we should use this processes for security.
HASHING
It should be used a hash function when we want to compare but can't store the plain value. Passwords should always be hashed . This is because we don't want recover the stored password rather we would compare betwwen stored and input data. We also use hashing to check for pirated files. It is also used to verify whether two files  are identical. This is helpful when we download a file from internet and can check successfully whether the downloaded file and file on server are same. Hash functions are also great for signing data. For example, if we are using HMAC, you sign a piece of data by taking a hash of the data concatenated with a known but not transmitted value (a secret value). So we send the plain-text and the HMAC hash. Then, the receiver simply hashes the submitted data with the known value and checks to see if it matches the transmitted HMAC. If it is the same, we know it wasn't tampered by a party without the secret value. This is commonly used in secure cookie systems by HTTP networks, as well as in message transmission of data over HTTP where we want some validity to the data.

The probability of a collision is astronomical for small input sizes. That's why it's recommended for passwords. For passwords up to 32 characters, MD5 has 4 times the output space. SHA-1 has about 6 times the output space. SHA-512 has about 16 times the output space. You must have seen that in many sites if you forgot your password then you are provided with a page to enter new password and old password is never recovered.
ENCRYPTION
Encryption should be used whenever we need to get the input data back out. If we are storing credit card numbers, we need to get them back out at some point of time, but don't want to store the plain text. So instead, store the encrypted version and keep the key as safe as possible. This key is important as if someone gets this key then the value can be decrypted very easily.
Saturday, January 5, 2013

Today I am going to post about security. Many of people has a misconception about hashing and encryption. Not only that many cannot understand when to use hashing and when to use encryption. So here we will discuss differences of hashing and encryption.
HASHING
They provide a mapping between an arbitrary length input, and usually fixed or smaller length output. It can be anything like simple CRC32, to a full blown cryptographic hash function such as MD5 , SHA-1/SHA-2/SHA-256/SHA-512. A one-way mapping is carried out. It's always a many:one mapping (there will always be collisions) since every function produces a smaller output than it's capable of inputting.
The reason they are hard and practically impossible to reverse is because of their algorithms. Most hash functions iterate over the input many times to produce the output. At each fixed length input (which is algorithm dependent), the hash function will call it its current state. It will then iterate over this state and change to a new one and use the result as feedback (MD5 do this 64 times for each of 512bits of data). It then combines the resultant states from all the iterations back together to form the resultant hash of the input.
Now, if we want to decode the hash, you'd first need to figure out how to split the given hash into its iterated states. Then we need to reverse the iteration for each state. Now, to explain why this is VERY HARD, think of trying to deduce x and y from : x + y=10. There are 10 positive combinations of x and y that can work. Now iterate over that a number of times: tmp = x + y; x = y; y = tmp. For 64 iterations, we will have 10^64 possibilities. Real hash functions do a lot more than one operation (MD5 does 15 operations on 4 state variables). And since the next iteration depends on the state of the previous and the previous is destroyed in creating the current state, it's all but impossible to determine the input state that led to a given output state. Brute-force is a better choice than decoding if the length of input is known.

ENCRYPTION
They provide a 1:1 mapping between an arbitrary length input and and output  and are always reversible. It is always 1:1 for a given key. Now, there are multiple input:key pairs that might generate the same output. Good encrypted data is indistinguishable from random noise. This is different from a hash output which is always of a consistent format.

Friday, January 4, 2013
Today I am going to post how you can display all the system properties with a simple Java program. You will need the java.util.Enumeration and java.util.Properties class. There is a method getProperties() defined in java.lang.System class. This method returns all the properties associated with your system as a Properties reference. Now we get an Enumeration of all keys of the properties. Next we iterate through each element of enumeration and get the value of individual keys and display them.
--------------------------------------------------------------------------------------------------------------------------
Java Source Code
--------------------------------------------------------------------------------------------------------------------------

import java.util.Enumeration;
import java.util.Properties;

public class SystemProperties{
public static void main (String[] args) {
Properties p=System.getProperties();  //getting system properties
Enumeration keys = p.keys();  //getting all keys of properties

        while (keys.hasMoreElements()) {
            String key = (String)keys.nextElement();  //getting next key
            String value = (String)p.get(key);  //getting key value
            System.out.println(key + ": " + value);
        }
    }
}
--------------------------------------------------------------------------------------------------------------------------
Output
--------------------------------------------------------------------------------------------------------------------------

java.runtime.name: Java(TM) SE Runtime Environment
sun.boot.library.path: C:\Program Files\Java\jdk1.7.0\jre\bin
java.vm.version: 21.0-b17
java.vm.vendor: Oracle Corporation
java.vendor.url: http://java.oracle.com/
path.separator: ;
java.vm.name: Java HotSpot(TM) Client VM
file.encoding.pkg: sun.io
user.country: US
user.script:
sun.java.launcher: SUN_STANDARD
sun.os.patch.level:
java.vm.specification.name: Java Virtual Machine Specification
user.dir: D:\Choto documents\Choto documents\Java Programs
java.runtime.version: 1.7.0-b147
java.awt.graphicsenv: sun.awt.Win32GraphicsEnvironment
java.endorsed.dirs: C:\Program Files\Java\jdk1.7.0\jre\lib\endorsed
os.arch: x86
java.io.tmpdir: C:\Users\Chelsea\AppData\Local\Temp\
line.separator:

java.vm.specification.vendor: Oracle Corporation
user.variant:
os.name: Windows 7
sun.jnu.encoding: Cp1252
java.library.path: C:\Program Files\Java\jdk1.7.0\bin;C:\Windows\Sun\Java\bin;C:\Windows\system32;C:\Windows;C:\Program Files\PC Connectivity Solution\;C:\Program Files\Java\jdk1.7.0\bin;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;.
java.specification.name: Java Platform API Specification
java.class.version: 51.0
sun.management.compiler: HotSpot Client Compiler
os.version: 6.1
user.home: C:\Users\Chelsea
user.timezone:
java.awt.printerjob: sun.awt.windows.WPrinterJob
file.encoding: Cp1252
java.specification.version: 1.7
java.class.path: D:\Java Programs;C:\Program Files\Java\jdk1.7.0\jre\lib\rt.jar;C:\Program Files\Java\jdk1.7.0\lib\dt.jar;C:\Program Files\Java\jdk1.7.0\lib\tools.jar;C:\Program Files\Java\jdk1.7.0\jre\lib\ext\dnsns.jar;C:\Program Files\Java\jdk1.7.0\jre\lib\ext\localedata.jar;C:\Program Files\Java\jdk1.7.0\jre\lib\ext\sunec.jar;C:\Program Files\Java\jdk1.7.0\jre\lib\ext\sunjce_provider.jar;C:\Program Files\Java\jdk1.7.0\jre\lib\ext\sunmscapi.jar;C:\Program Files\Java\jdk1.7.0\jre\lib\ext\sunpkcs11.jar;C:\Program Files\Java\jdk1.7.0\jre\lib\ext\zipfs.jar
user.name: -MadMickael/FFF
java.vm.specification.version: 1.7
sun.java.command: SystemProperties
java.home: C:\Program Files\Java\jdk1.7.0\jre
sun.arch.data.model: 32
user.language: en
java.specification.vendor: Oracle Corporation
awt.toolkit: sun.awt.windows.WToolkit
java.vm.info: mixed mode, sharing
java.version: 1.7.0
java.ext.dirs: C:\Program Files\Java\jdk1.7.0\jre\lib\ext;C:\Windows\Sun\Java\lib\ext
sun.boot.class.path: C:\Program Files\Java\jdk1.7.0\jre\lib\resources.jar;C:\Program Files\Java\jdk1.7.0\jre\lib\rt.jar;C:\Program Files\Java\jdk1.7.0\jre\lib\sunrsasign.jar;C:\Program Files\Java\jdk1.7.0\jre\lib\jsse.jar;C:\Program Files\Java\jdk1.7.0\jre\lib\jce.jar;C:\Program Files\Java\jdk1.7.0\jre\lib\charsets.jar;C:\Program Files\Java\jdk1.7.0\jre\classes
java.vendor: Oracle Corporation
file.separator: \
java.vendor.url.bug: http://bugreport.sun.com/bugreport/
sun.io.unicode.encoding: UnicodeLittle
sun.cpu.endian: little
sun.desktop: windows
sun.cpu.isalist: pentium_pro+mmx pentium_pro pentium+mmx pentium i486 i386 i86
--------------------------------------------------------------------------------------------------------------------------

Download Links
--------------------------------------------------------------------------------------------------------------------------
DOWNLOAD the source from Mediafire
DOWNLOAD the source from 4shared
Tuesday, January 1, 2013
Today I am going to post a program that will be able to display i.e list all the files and folders in your computer. Here we have used the java.io.File class for this purpose. At first we call the listRoots() function to list all the drives. Then for each drive we list all of their contents. A recursive function is defined that takes in a reference of File class instance as parameter. Now if it is a file then its absolute path is displayed. If it is a folder then all the contents of this directory is listed and kept in a File array. Now for each of the elements of the array the recursive function is called. The contents are listed following DFS algorithm.
--------------------------------------------------------------------------------------------------------------------------
Java Source Code
--------------------------------------------------------------------------------------------------------------------------


import java.io.File;
public class FileList {

    static void list(File f){
        if (f.isFile()){
            System.out.println(f.getAbsolutePath()); //displays path for a file
            return;
        }
        else{
            File dir_list[]=f.listFiles();  //lists all contents if a directory
            for (File t : dir_list)
                try{
                  list(t);  //calls list for each content of directory
                }catch(Exception e){
                  e.printStackTrace();
                }
        }
    }
   
    public static void main(String[] args){
        File drive_list[]=File.listRoots();  //lists all drives
           try{
               for(File drive : drive_list)
                  list(drive);  //calls recur for each drive
            }catch(Exception e){
              e.printStackTrace();
            }       
    }
}
--------------------------------------------------------------------------------------------------------------------------
Download Links
--------------------------------------------------------------------------------------------------------------------------
DOWNLOAD the source from Mediafire
DOWNLOAD the source from 4shared

Total Pageviews

Followers


Labels

Popular Posts

free counters