Friday, May 24, 2013

How to read certificates using CertificateFactory class

In my previous blog, I have explained how can you create self signed certificate using bouncy castle API and how to import it into keystore.

This tutorial will explain how to read existing certificate file using java.security.cert.CertificateFactory class.


import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.security.KeyStore;
import java.security.PublicKey;
import java.security.cert.Certificate;
import java.security.cert.CertificateFactory;

/**
 * Reads the certificate and import into Java keystore.
 *
 * @author abdul
 *
 */
public class ReadCertificateFile {

    /**
     * @param args
     * @throws Exception
     */
    public static void main(String[] args) throws Exception {

        ReadCertificateFile readCertificateFile = new ReadCertificateFile();

        // Path of the certificate file
        FileInputStream fis = new FileInputStream("YOUR_CERTIFICATE.cert");

        /*
         * Returns a CertificateFactory object of the specified certificate
         * type.
         */
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
       
        /*
         * Read the certificate from the specified input stream, and returns it
         * as a Certificate object. It can read certificate in both binary (DER
         * encoded) and printable (RFC standard) formats.
         */
        java.security.cert.Certificate cert = cf.generateCertificate(fis);

        System.out.println();
        System.out.println("Certificate Details: ");
        /*Returns the type of this certificate factory*/
        System.out.println("Type = " + cert.getType());
       
        System.out.println("toString = " + cert.toString());

        PublicKey key = cert.getPublicKey();
        System.out.println();
        System.out.println("PublicKey Object Info: ");
        System.out.println("Algorithm = " + key.getAlgorithm());
        System.out.println("Format = " + key.getFormat());
        System.out.println("toString = " + key.toString());

        // save/import certificate into keystore
        readCertificateFile.saveCert(cert);
    }

    private void saveCert(Certificate cert) throws Exception {
        KeyStore keyStore = KeyStore.getInstance("JKS");
        keyStore.load(null, null);

        // import your certificate into keystore
        keyStore.setCertificateEntry("YOUR_ALIAS_NAME", cert);

        // name of keystore "
        File file = new File(".", "YOUR_KEYSTORE_NAME");
        keyStore.store(new FileOutputStream(file),
                "YOUR_PASSWORD".toCharArray());
    }

}


Tuesday, April 9, 2013

Eclipse - Tips & Tricks

This article is for those who use Eclipse. Keyboards shortcuts are very important for comfortable and quick editing. Here are the list of most important shortcuts in Eclipse :
For a full list of shortcuts, you can also check by pressing Ctrl+Shift+L.
  1. Ctrl +3 Focus into the Quick Access search box which allows you to execute any Eclipse command.
  2. Ctrl+SHIFT+T Search dialog for Java Type, Start typing the name and the list gets smaller. Try typing the capital letters of the class only (e.g. type "NPE" to find "NullPointerException")
  3. Ctrl+SHIFT+R Search dialog for resources, e.g. Xml files, text files, or files of any other type.
  4. Ctrl+E Open Editor Drop down, Presents a popup window listing currently opened files.
  5. Ctrl+O Quick Outline, Show all methods of the current class, Press Ctrl+O a second time to include inherited methods.
  6. Ctrl+SHIFT+space Context Information
  7. Ctrl+Shift+O Organize Imports, Adjusts the imports statements in the current Java source file
  8. F3 Open Declaration ,Navigate to the declaration of the selected variable . This works much like a browser hyperlink.
  9. Ctrl + hover to methods,variables Ask for Open Declaration, Implementation, Super Implementation or return types.
  10. Alt+Left/Right Backward/Forward History, Works like a browser's back/forward button.
  11. Ctrl + L Go to a specific line number.
  12. F4 Open Type Hierarachy
  13. Ctrl+Alt+H Open Call Hierarchy. Show where a method is called from.
  14. Alt + SHIFT + R Use this to rename type, method, or field. All existing references will be refactored as well.
  15. Alt+Shift+M Extract method, Use this to extract a new method from existing code. The parameter list and return type will be automatically created.
  16. Ctrl+Shift+P Go to the matching bracket.
  17. SHIFT+ENTER /Ctrl+SHIFT+ENTER Insert a line below or above the current line.
  18. Ctrl + /, Ctrl+7, Ctrl +\ Add or Remove block comment.
  19. Ctrl +F6 Switch among the editor.
  20. Ctrl + F7 Switch among open views.
  21. Ctrl + F8 Switch among perspectives.
  22. Alt +/ It does the word completion based on the set of words already present in the current file.
  23. Ctrl + I It correct the indention for block of Java code or an entire class.
  24. Ctrl + . or Ctrl + , It will navigate to next or previous error.
  25. Ctrl+F11, F11, Run or Debug the Application.
  26. F5,F6, F7, F8 Step into function, Next Step (line by line) , Step out , Skip to next breakpoint.
  27. Ctrl +1 Give quick fix code.
  28. Ctrl + D Delete the current line.
  29. Ctrl + SHIFT + G Search for current cursor positioned word reference in workspace.
  30. Ctrl +Page Up/Page Down Switch to next editor / switch to previous editor
  31. Alt + - Open Editor Window Option menu.
  32. Ctrl +F10, then n It will show or hide the line numbers
  33. Ctrl + q It will jump to last location edited
  34. Ctrl + SHIFT + f It will format all code in Editor using code formatter.
  35. Alt + SHIFT + J or /** and then press Enter Add javadoc Element Comment ( adds '/** ... */')
  36. Alt + SHIFT + V Move selected element to other class or file (With complete method or class selected)
  37. Ctrl + DEL Delete next element
  38. Ctrl + BACKSPACE Delete previous element. 
    Note : I have not added basic shortcut like Ctrl+S to save the file.
    Feel free to comment If you find something is incorrect or update me more :)

Wednesday, April 3, 2013

Hibernate Configuration

To inform Hibernate from where to find mapping information of Java classes to database tables or configuration setting related to database, All such information is usually supplied by Hibernate Configuration Object. It is managed by an instance of org.hibernate.cfg.Configuration. An instance of org.hibernate.cfg.Configuration represents an entire set of mappings of an application’s Java types to an SQL database. The mappings are compiled from various XML mapping files or from Java 5 Annotations.

Hibernate provides following types of configurations
  1. hibernate.cfg.xml – A standard XML file which contains hibernate configuration and which resides in root of application’s CLASSPATH 
  2. hibernate.properties – A Java compliant property file which holds key value pair for different hibernate configuration strings. 
  3. Programmatic configuration – This is the manual approach. The configuration can be defined in Java class. 

1. hibernate.cfg.xml : The hibernate.cfg.xml file is a standard XML file which contains all the configuration parameters like database connection, class mappings etc. This file needs to be placed root of CLASSPATH of application.

Below is the sample hibernate.cfg.xml file :
 
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration> <session-factory>
<!-- Database connection settings -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost/SampleApp</property>
<property name="connection.username">root</property>
<property name="connection.password">root123</property>
<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</property>
<!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- Enable Hibernate's automatic session context management -->
<property name="current_session_context_class">thread</property>
<!-- Disable the second-level cache -->
<property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
<!-- Echo all executed SQL to stdout -->
<property name="show_sql">false</property>
<!-- Drop and re-create the database schema on startup -->
<property name="hbm2ddl.auto">update</property>
<!-- Mapping files POJO -->
<mapping class="com.hibernate.pojo.Host"/>
</session-factory>
</hibernate-configuration>

2. hibernate.properties file :
This is the easiest way to get started with Hibernate. Create a file hibernate.properties and place it in root of your applications CLASSPATH.
 
Below is the sample hibernate.properties file:

hibernate.connection.driver_class=com.mysql.jdbc.Driver
hibernate.connection.url=jdbc:mysql://localhost/SampleApp
hibernate.connection.username=root
hibernate.connection.password=root123
hibernate.connection.pool_size=1
hibernate.dialect = org.hibernate.dialect.MySQLDialect
 3. Programmatic Configuration

We can obtain a org.hibernate.cfg.Configuration instance by instantiating it directly and specifying XML mapping documents. If the mapping files are in the classpath, use addResource(). For example:
Configuration cfg = new Configuration()
.addResource("Host.hbm.xml");

An alternative way is to specify the mapped class and allow Hibernate to find the mapping document for you:
Configuration cfg = new Configuration()
.addClass(com.hibernate.pojo.Host.class);

A org.hibernate.cfg.Configuration also allows you to specify configuration properties. For example:
 Configuration cfg = new Configuration()
.addClass(com.hibernate.pojo.Host.class)
.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQLDialect")
.setProperty("hibernate.connection.datasource", "jdbc:mysql://localhost/SampleApp")
.setProperty("hibernate.order_updates", "true");

Refer here for more details :
http://docs.jboss.org/hibernate/core/3.6/reference/en-US/html/session-configuration.html#configuration-optional 

How TOPT Works: Generating OTPs Without Internet Connection

Introduction Have you ever wondered how authentication apps like RSA Authenticator generate One-Time Passwords (OTPs) without requiring an i...