Showing posts with label Java Security. Show all posts
Showing posts with label Java Security. Show all posts

Wednesday, September 21, 2011

How to generate a file checksum value in Java

package org.best.example; 
import java.io.FileInputStream;
import java.security.MessageDigest;
 
public class TestCheckSum {
 
  public static void main(String args[]) throws Exception {
 
    String datafile = "c:\\INSTLOG.TXT";
 
    MessageDigest md = MessageDigest.getInstance("SHA1");
    FileInputStream fis = new FileInputStream(datafile);
    byte[] dataBytes = new byte[1024];
 
    int nread = 0; 
 
    while ((nread = fis.read(dataBytes)) != -1) {
      md.update(dataBytes, 0, nread);
    };
 
    byte[] mdbytes = md.digest();
 
    //convert the byte to hex format
    StringBuffer sb = new StringBuffer("");
    for (int i = 0; i < mdbytes.length; i++) 
{
 sb.append(Integer.toString((mdbytes[i] & 0xff) + 0x100, 16).substring(1));
    }
 
    System.out.println("Digest(in hex format):: " + sb.toString());
 
  }
}

Friday, September 9, 2011

Blowfish Cipher Security

package org.best.example;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.swing.JOptionPane;

/**
 * This program demonstrates how to encrypt/decrypt input
 * using the Blowfish Cipher with the Java Cryptograhpy.
 *
 */
public class BlowfishCipher {

  public static void main(String[] args) throws Exception {

    // create a key generator based upon the Blowfish cipher
    KeyGenerator keygenerator = KeyGenerator.getInstance("Blowfish");

    // create a key
    SecretKey secretkey = keygenerator.generateKey();

    // create a cipher based upon Blowfish
    Cipher cipher = Cipher.getInstance("Blowfish");

    // initialise cipher to with secret key
    cipher.init(Cipher.ENCRYPT_MODE, secretkey);

    // get the text to encrypt
    String inputText = JOptionPane.showInputDialog("Input your message: ");

    // encrypt message
    byte[] encrypted = cipher.doFinal(inputText.getBytes());

    // re-initialise the cipher to be in decrypt mode
    cipher.init(Cipher.DECRYPT_MODE, secretkey);

    // decrypt message
    byte[] decrypted = cipher.doFinal(encrypted);

    // and display the results
    JOptionPane.showMessageDialog(JOptionPane.getRootFrame(),
                                  "encrypted text: " + new String(encrypted) + "\n" +
                                  "decrypted text: " + new String(decrypted));

    // end example
    System.exit(0);
  }
}

Thursday, September 8, 2011

Byte Utils security in java

package org.best.example;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class ByteUtils {
  private static final int DEFAULT_CHUNK_SIZE = 1024;


  /**
   * save bytes to file
   * @param fileName the file to write the supplied bytes
   * @param theBytes the bytes to write to file
   * @throws java.io.IOException reports problems saving bytes to file
   */
  public static void saveBytesToFile( String fileName, byte[] theBytes )
      throws java.io.IOException {
    saveBytesToStream( new java.io.FileOutputStream( fileName ), theBytes );
  }

  /**
   * save bytes to output stream and close the output stream on success and
   * on failure.
   * @param out the output stream to write the supplied bytes
   * @param theBytes the bytes to write out
   * @throws java.io.IOException reports problems saving bytes to output stream
   */
  public static void saveBytesToStream( java.io.OutputStream out, byte[] theBytes )
      throws java.io.IOException {
    try {
      out.write( theBytes );
    }
    finally {
      out.flush();
      out.close();
    }
  }

  /**
   * Loads bytes from the file
   *
   * @param fileName file to read the bytes from
   * @return bytes read from the file
   * @exception java.io.IOException reports IO failures
   */
  public static byte[] loadBytesFromFile( String fileName ) throws java.io.IOException {
    return loadBytesFromStream( new java.io.FileInputStream( fileName ), DEFAULT_CHUNK_SIZE );
  }

  /**
   * Loads bytes from the given input stream until the end of stream
   * is reached.  It reads in at kDEFAULT_CHUNK_SIZE chunks.
   *
   * @param stream to read the bytes from
   * @return bytes read from the stream
   * @exception java.io.IOException reports IO failures
   */
  public static byte[] loadBytesFromStream( java.io.InputStream in ) throws java.io.IOException {
    return loadBytesFromStream( in, DEFAULT_CHUNK_SIZE );
  }

  /**
   * Loads bytes from the given input stream until the end of stream
   * is reached.  Bytes are read in at the supplied <code>chunkSize</code>
   * rate.
   *
   * @param stream to read the bytes from
   * @return bytes read from the stream
   * @exception java.io.IOException reports IO failures
   */
  public static byte[] loadBytesFromStream( java.io.InputStream in, int chunkSize )
      throws java.io.IOException {
    if( chunkSize < 1 )
      chunkSize = DEFAULT_CHUNK_SIZE;

    int count;
    java.io.ByteArrayOutputStream bo = new java.io.ByteArrayOutputStream();
    byte[] b = new byte[chunkSize];
    try {
      while( ( count = in.read( b, 0, chunkSize ) ) > 0 ) {
        bo.write( b, 0, count );
      }
      byte[] thebytes = bo.toByteArray();
      return thebytes;
    }
    finally {
      bo.close();
    }
  }
}

Wednesday, September 7, 2011

Accessing Security Certificates

package org.best.example;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.security.KeyStore;
import java.security.PrivateKey;
import java.security.cert.Certificate;
import java.util.Enumeration;

public class AccessingCertificates {

  public static void main( String[] args ) throws Exception {
    final String keyStore = "acme";
    final String keyStorePass = "danger";
    final String keyPass = "password";

    // load information into a keystore
    java.security.KeyStore ks = java.security.KeyStore.getInstance( "JKS" );
    java.io.FileInputStream ksfis = new java.io.FileInputStream( keyStore );
    java.io.BufferedInputStream ksbufin = new java.io.BufferedInputStream( ksfis );
    ks.load( ksbufin, keyStorePass.toCharArray() );

    // list aliases in the keystore
    java.io.FileOutputStream fos = null;
    for( java.util.Enumeration theAliases = ks.aliases(); theAliases.hasMoreElements(); ) {
      String alias = (String) theAliases.nextElement();
      java.security.cert.Certificate cert = ks.getCertificate( alias );
      ByteUtils.saveBytesToFile( alias + ".cer", cert.getEncoded() );
      ByteUtils.saveBytesToFile( alias + ".pubkey", cert.getPublicKey().getEncoded() );
      java.security.PrivateKey privateKey = (java.security.PrivateKey) ks.getKey( alias, keyPass.toCharArray() );
      ByteUtils.saveBytesToFile( alias + ".privKey", privateKey.getEncoded() );
      System.out.println( "### generated certificate information for -> " + alias );
      System.out.println( cert );
    }
  }
}

Thursday, June 23, 2011

How to Do Hashing String with SHA-256

It will use SHA-256 hashing algorithm to generate a hash value for a password “123456″.

package org.best.example;
 
import java.security.MessageDigest;
 
public class SHAHashingExample 
{
    public static void main(String[] args)throws Exception
    {
     String password = "123456";
 
        MessageDigest md = MessageDigest.getInstance("SHA-256");
        md.update(password.getBytes());
 
        byte byteData[] = md.digest();
 
        //convert the byte to hex format method 1
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < byteData.length; i++) {
         sb.append(Integer.toString((byteData[i] & 0xff) + 0x100, 16).substring(1));
        }
 
        System.out.println("Hex format : " + sb.toString());
 
        //convert the byte to hex format method 2
        StringBuffer hexString = new StringBuffer();
     for (int i=0;i<byteData.length;i++) {
      String hex=Integer.toHexString(0xff & byteData[i]);
          if(hex.length()==1) hexString.append('0');
          hexString.append(hex);
     }
     System.out.println("Hex format : " + hexString.toString());
    }
}
Output
Hex format : 8d969eef6ecad3c29a3a629280e686cf0c3f5d5a86aff3ca12020c923adc6c92
Hex format : 8d969eef6ecad3c29a3a629280e686cf0c3f5d5a86aff3ca12020c923adc6c92

Wednesday, June 22, 2011

How to Do Java SHA Hashing

SHA-2 is believe the most secure hashing algorithm as this article is written, here are few examples for the SHA implementation. The possible MessageDigest algorithm are SHA-1, SHA-256, SHA-384, and SHA-512, you can check the reference for the detail.It will use SHA-256 hashing algorithm to generate a checksum for file “c:\\loging.log”.

package org.best.example;
 
import java.io.FileInputStream;
import java.security.MessageDigest;
 
public class SHACheckSumExample 
{
    public static void main(String[] args)throws Exception
    {
        MessageDigest md = MessageDigest.getInstance("SHA-256");
        FileInputStream fis = new FileInputStream("c:\\loging.log");
 
        byte[] dataBytes = new byte[1024];
 
        int nread = 0; 
        while ((nread = fis.read(dataBytes)) != -1) {
          md.update(dataBytes, 0, nread);
        };
        byte[] mdbytes = md.digest();
 
        //convert the byte to hex format method 1
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < mdbytes.length; i++) {
          sb.append(Integer.toString((mdbytes[i] & 0xff) + 0x100, 16).substring(1));
        }
 
        System.out.println("Hex format : " + sb.toString());
 
       //convert the byte to hex format method 2
        StringBuffer hexString = new StringBuffer();
     for (int i=0;i<mdbytes.length;i++) {
       hexString.append(Integer.toHexString(0xFF & mdbytes[i]));
     }
 
     System.out.println("Hex format : " + hexString.toString());
    }
}
 
Output
 
Hex format : 21a57f2fe765e1ae4a8bf15d73fc1bf2a533f547f2343d12a499d9c0592044d4
Hex format : 21a57f2fe765e1ae4a8bf15d73fc1bf2a533f547f2343d12a499d9c0592044d4