Wednesday, October 28, 2015

Encryption and decryption in java using private key


import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.spec.AlgorithmParameterSpec;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.KeySpec;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.PBEParameterSpec;

import org.springframework.stereotype.Component;

/**
 * @author lovebharti
 */
@Component
public class CryptoUtil {

    private Cipher cipher;
    private Cipher decipher;
    private int iterationCount = 19;
   
    private String secretKeyFactory="PBEWithMD5AndDES";

    private byte[] salt = {
        (byte) 0xA9, (byte) 0x9B, (byte) 0xC8, (byte) 0x32,
        (byte) 0x56, (byte) 0x35, (byte) 0xE3, (byte) 0x03
    };

    /**
     * @param secretKey Key used to encrypt data
     * @param plainText Text input to be encrypted
     * @return Returns encrypted text
     */
    public String encrypt(String secretKey, String plainText)
            throws NoSuchAlgorithmException,
            InvalidKeySpecException,
            NoSuchPaddingException,
            InvalidKeyException,
            InvalidAlgorithmParameterException,
            UnsupportedEncodingException,
            IllegalBlockSizeException,
            BadPaddingException{
        //Key generation for enc and desc
        KeySpec keySpec = new PBEKeySpec(secretKey.toCharArray(), salt, iterationCount);
        SecretKey key = SecretKeyFactory.getInstance(secretKeyFactory).generateSecret(keySpec);      
         // Prepare the parameter to the ciphers
        AlgorithmParameterSpec paramSpec = new PBEParameterSpec(salt, iterationCount);

        //Enc process
        cipher = Cipher.getInstance(key.getAlgorithm());
        cipher.init(Cipher.ENCRYPT_MODE, key, paramSpec);  
        String charSet="UTF-8";      
        byte[] in = plainText.getBytes(charSet);
        byte[] out = cipher.doFinal(in);
        String encStr=new sun.misc.BASE64Encoder().encode(out);
        return encStr;
    }
   
   
    /**    
     * @param secretKey Key used to decrypt data
     * @param encryptedText encrypted text input to decrypt
     * @return Returns plain text after decryption
     */
    public String decrypt(String secretKey, String encryptedText)
     throws NoSuchAlgorithmException,
            InvalidKeySpecException,
            NoSuchPaddingException,
            InvalidKeyException,
            InvalidAlgorithmParameterException,
            UnsupportedEncodingException,
            IllegalBlockSizeException,
            BadPaddingException,
            IOException{
         //Key generation for enc and desc
        KeySpec keySpec = new PBEKeySpec(secretKey.toCharArray(), salt, iterationCount);
        SecretKey key = SecretKeyFactory.getInstance(secretKeyFactory).generateSecret(keySpec);      
         // Prepare the parameter to the ciphers
        AlgorithmParameterSpec paramSpec = new PBEParameterSpec(salt, iterationCount);
        //Decryption process; same key will be used for decr
        decipher=Cipher.getInstance(key.getAlgorithm());
        decipher.init(Cipher.DECRYPT_MODE, key,paramSpec);
        byte[] enc = new sun.misc.BASE64Decoder().decodeBuffer(encryptedText);
        byte[] utf8 = decipher.doFinal(enc);
        String charSet="UTF-8";    
        String plainStr = new String(utf8, charSet);
        return plainStr;
    }  
}

Thursday, June 11, 2015

Adding virtual host in apache

1. Go to : /etc/apache2/sites-available
2. Add/create cg.xyz.com.conf file using sudo

 <VirtualHost *:80>
    # The ServerName directive sets the request scheme, hostname and port that
    # the server uses to identify itself. This is used when creating
    # redirection URLs. In the context of virtual hosts, the ServerName
    # specifies what hostname must appear in the request's Host: header to
    # match this virtual host. For the default virtual host (this file) this
    # value is not decisive as it is used as a last resort host regardless.
    # However, you must set it for any further virtual host explicitly.
    #ServerName www.example.com

    ServerAdmin webmaster@cg.yatra.com
    DocumentRoot /var/www

    # Available loglevels: trace8, ..., trace1, debug, info, notice, warn,
    # error, crit, alert, emerg.
    # It is also possible to configure the loglevel for particular
    # modules, e.g.
    #LogLevel info ssl:warn

    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined

    # For most configuration files from conf-available/, which are
    # enabled or disabled at a global level, it is possible to
    # include a line for only one particular virtual host. For example the
    # following line enables the CGI configuration for this host only
    # after it has been globally disabled with "a2disconf".
    #Include conf-available/serve-cgi-bin.conf
</VirtualHost>

# vim: syntax=apache ts=4 sw=4 sts=4 sr noet

3. now make a link of above created file in /etc/apache2/sites-enabled of same name

4. Activate the host now : sudo a2ensite  cg.xyz.com

5. restart apache service
sudo service apache2 restart


Sunday, December 1, 2013

Hibernate Util

package com.impetus.smarttravelportal.dao.impl;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;

/**
 * @author premkumar.bharti HibernateUtil creates sessions for daolayer
 */
@SuppressWarnings("all")
public final class HibernateUtil {
    private static SessionFactory sessionFactory = null;
   
    /**
     * creates a session with the database.
     *
     * @return session factory object.
     */
    @SuppressWarnings("deprecation")
    private static SessionFactory buildSessionFactory() {
       
        if (sessionFactory == null) {
            try {
               
                if (sessionFactory == null) {
                    sessionFactory = new AnnotationConfiguration().configure()
                            .buildSessionFactory();
                } else {
                    return sessionFactory;
                }
            } catch (Exception ex) {
               
                throw new ExceptionInInitializerError(ex);
            }
        }
        return sessionFactory;
    }
   
    /**
     * return SessionFactory to get new Session out of it
     *
     * @return SessionFactory
     */
    public static SessionFactory getSessionFactory() {
        return buildSessionFactory();
    }
   
    private HibernateUtil() {
       
    }
}

Logging Interceptor

import org.sonar.report.pdf.util.Logger;

import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.Interceptor;

/**
 * @author premkumar.bharti Logging Interceptor handles logging.
 */
public class LoggingInterceptor implements Interceptor {
   
    private static final long serialVersionUID = 1L;
   
    /**
     * Interceptor acts when Action Class starts and exists
     */
    public String intercept(ActionInvocation invocation) {
        String result = null;
       
        @SuppressWarnings("unused")
        String className = invocation.getAction().getClass().getName();
        try {
            result = invocation.invoke();
        } catch (Exception ex) {
            return null;
        }
        return result;
    }
   
    /**
     * called at destruction of Action
     */
    public void destroy() {
        Logger.info("Destroyed-----------");
       
    }
   
    /**
     * called at initialisation of Action
     */
    public void init() {
        Logger.info("Initialised-----------");
       
    }
}

Date Converter Util

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * @author premkumar.bharti DateUtil mainly handle date operation like
 *         converting from one form to another.
 */
public final class DateUtil {
    /**
     * private Constructor
     */
    private DateUtil() {
    }
   
    /**
     * converts date to format yyyy/mm/dd.
     *
     * @param date
     * @return
     * @throws ParseException
     */
    public static Date dateConvertor(String date, String format)
            throws ParseException {
       
        DateFormat parser = new SimpleDateFormat(format);
        return parser.parse(date);
    }
   
    /**
     * adds date with the number of days present
     *
     * @param date
     * @param days
     * @return
     */
    @SuppressWarnings("static-access")
    public static String myAddDate(Date date, int days) throws ParseException {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.add(cal.DATE, Const.THREE);
        String fdate = cal.get(Calendar.DATE) + "/"
                + (cal.get(Calendar.MONTH) + 1) + "/" + cal.get(Calendar.YEAR);
        return fdate;
    }  
}

Password and Retype Password check

1. pwd => first password field id
2. rpassword => retype password field id
3. notmatch=> where info will be displayed id


function check() {
var pwd = document.getElementById("pwd").value;
var rpassword = document.getElementById("rpassword").value;
if (pwd == rpassword) {
document.getElementById("notmatch").innerHTML = "";
} else {
document.getElementById("rpassword").value = "";
document.getElementById("notmatch").innerHTML = "Password don't match";
}
}

Ajax Form Submit

1. ('#register') => Form's id
2. $('#advert') => where response has to load

<script>
$('#register').submit(function() { // catch the form's submit event
$.ajax({ // create an AJAX call...
data : $(this).serialize(), // get the form data
type : $(this).attr('method'), // GET or POST
url : $(this).attr('action'), // the file to call
success : function(response) { // on success..
$('#advert').load('Views/userAdded.jsp'); }
});
return false; // cancel original event to prevent form submitting
});
</script>