encryption Posts

A Simple AES Encryption – Decryption Using Java

Several days ago, my friend asked me how to create a simple AES encryption – decryption using java. Well, here is your answer, hope it will helped you.

package com.edw.testing;

import java.security.AlgorithmParameters;
import java.security.spec.KeySpec;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;
import sun.misc.BASE64Encoder;

public class TestingAES {

    public TestingAES() {
    }

    private void execute() throws Exception {
        
        String password = "mypassword";
        String salt = "salt";
        String cipherText = "Hello, World!";
        
        SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
        KeySpec spec = new PBEKeySpec(password.toCharArray(), salt.getBytes(), 65536, 256);
        SecretKey tmp = factory.generateSecret(spec);
        SecretKey secret = new SecretKeySpec(tmp.getEncoded(), "AES");

        // encrypt
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, secret);
        AlgorithmParameters params = cipher.getParameters();
        byte[] iv = params.getParameterSpec(IvParameterSpec.class).getIV();
        byte[] ciphertext = cipher.doFinal(cipherText.getBytes("UTF-8"));
        
        System.out.println("password : "+password);
        System.out.println("salt : "+salt);
        System.out.println("cipherText : "+cipherText);
        System.out.println("iv : "+new BASE64Encoder().encode(iv));
        System.out.println("ciphertext : "+new BASE64Encoder().encode(ciphertext));
        
        // decrypt
        Cipher cipherDecrypt = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipherDecrypt.init(Cipher.DECRYPT_MODE, secret, new IvParameterSpec(iv));
        String plaintext = new String(cipherDecrypt.doFinal(ciphertext), "UTF-8");
        System.out.println("decrypted text : "+plaintext);
        
    }

    public static void main(String[] args) throws Exception {
        TestingAES testingAES = new TestingAES();
        testingAES.execute();
    }
}

And this is what is written on my netbeans console,

Oh and if you ever found this kind of error

Caused by: java.security.InvalidKeyException: Illegal key size or default parameters

it means that you need to install Java Cryptography Extension (JCE). You will find it here,


http://www.oracle.com/technetwork/java/javase/downloads/jce-6-download-429243.html

Have fun :-D

Google+

A Simple Blowfish Encryption / Decryption using Java

This is a simple encryption using Blowfish Algorithm that i use to encrypt several properties on my application. On this example im using username appended with password as salt to encrypt password variables.

package com.edw.main;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

public class BlowfishTest {

    public static void main(String[] args) throws Exception {
        encrypt("edwin","password");
        decrypt("6VsVtA/nhHKUZuWWmod/BQ==");
    }

    private static void encrypt(String username, String password) throws Exception {
        byte[] keyData = (username+password).getBytes();
        SecretKeySpec secretKeySpec = new SecretKeySpec(keyData, "Blowfish");
        Cipher cipher = Cipher.getInstance("Blowfish");
        cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
        byte[] hasil = cipher.doFinal(password.getBytes());
        System.out.println(new BASE64Encoder().encode(hasil));
    }
    
    private static void decrypt(String string) throws Exception {
        byte[] keyData = ("edwin"+"password").getBytes();
        SecretKeySpec secretKeySpec = new SecretKeySpec(keyData, "Blowfish");
        Cipher cipher = Cipher.getInstance("Blowfish");
        cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
        byte[] hasil = cipher.doFinal(new BASE64Decoder().decodeBuffer(string));
        System.out.println(new String(hasil));
    }
}
Google+

Integrating BCrypt Hashing With Hibernate Framework

In this example, im trying to simulate a simple login to MySQL database. Usually i hash password value using MD5, but now im trying to do hashing using BCrypt Algorithm. Im using a simple java BCrypt class downloaded from here.

First as always, a simple table and row.

CREATE TABLE `users` (
  `username` varchar(20) NOT NULL DEFAULT '',
  `pwd` varchar(80) DEFAULT NULL,
  PRIMARY KEY (`username`)
)

insert into `users`(`username`,`pwd`) values ('edwin','$2a$12$bUwElzXYO116G6x.fLm5FOAJNB46R0974sAh2TQumJei4ia.x0YPy');

Next is creating a simple java class and xml to represent database tables.

package com.edw.bean;

public class Users  implements java.io.Serializable {

     private String username;
     private String pwd;

    public Users() {
    }

	// other setter and getter
}
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
    <class name="com.edw.bean.Users" table="users" catalog="test">
        <id name="username" type="string">
            <column name="username" length="20" />
            <generator class="assigned" />
        </id>
        <property name="pwd" type="string">
            <column name="pwd" length="80" />
        </property>
    </class>
</hibernate-mapping>

Next is my hibernate.cfg.xml configuration

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
  <session-factory>
    <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
    <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
    <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/test</property>
    <property name="hibernate.connection.username">root</property>
    <property name="hibernate.connection.password">****</property>
    <mapping resource="com/edw/bean/Users.hbm.xml"/>
  </session-factory>
</hibernate-configuration>

And my java class to load hibernate.cfg.xml

package com.edw.util;

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

public class HibernateUtil {

    private static final SessionFactory sessionFactory;
    
    static {
        try {           
            sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
        } catch (Throwable ex) {            
            System.err.println("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }
    
    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }
}

And this is my Main java class,

package com.edw.main;

import com.edw.bean.Users;
import com.edw.util.BCrypt;
import com.edw.util.HibernateUtil;
import org.apache.log4j.Logger;
import org.hibernate.Session;

public class Main {
    
    private static Logger logger = Logger.getLogger(Main.class );
    
    private Boolean startApp(String username, String password) {
        Session session = HibernateUtil.getSessionFactory().openSession();
        try {
            Users user = (Users)session.createQuery("from Users where username = :username")
                    .setString("username", username)
                    .uniqueResult();      
            // compare password with database's encrypted password
            if(BCrypt.checkpw(password, user.getPwd()))
                return true;
            return false;
        } catch (Exception e) {
            logger.error(e,e);
        } finally {            
            session.close();
        }
        return false;
    }
    
    private String hashPassword(String password) {
        return BCrypt.hashpw(password, BCrypt.gensalt(12));
    }
    
    public static void main(String[] args) {
        Main main = new Main();
        boolean success = main.startApp("edwin", "12345");
        if(success)
            logger.debug("Password is Right");
        else
            logger.debug("Password is Wrong");
        
        // simulate 10 hashed string password
        for (int i = 0; i < 10; i++) {
            logger.debug(main.hashPassword("12345"));
        }        
    }
}

This is my Netbeans project structure,

And this is my Netbean’s console

Google+

Creating an MD5 String using Java

MD5 is a simple cryptographic hashing algorithm widely used for various application. In this tutorial im trying to generate MD5 value from a string and then compare it to mysql’s MD5 query result.

This is my java code to generate MD5, im using java’s MessageDigest.

package com.edw.util;

import java.security.MessageDigest;
import org.junit.Test;

/**
 *
 * @author edw
 */
public class MD5Test {

    public MD5Test() {
    }

    public String hexStringFromBytes(byte[] b) {
        char[] hexChars = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
        String hex = "";
        int msb;
        int lsb = 0;
        int i;

        for (i = 0; i < b.length; i++) {
            msb = ((int) b[i] & 0x000000FF) / 16;
            lsb = ((int) b[i] & 0x000000FF) % 16;
            hex = hex + hexChars[msb] + hexChars[lsb];
        }
        return hex;
    }

    @Test
    public void testMD5() throws Exception {
        MessageDigest digest = java.security.MessageDigest.getInstance("MD5");
		
		// get md5 for word "PASSWORD"
        digest.update("PASSWORD".getBytes());
        byte[] passwordBytes = digest.digest();

		// result = 319f4d26e3c536b5dd871bb2c52e3178
        System.out.println(hexStringFromBytes(passwordBytes));		
    }
}

compared to mysql’s md5 function

you can see that MD5 strings generated by java and mysql are both the same.
(H)

Google+

encrypting ibatis’ sqlmapconfig.xml

after im writing this article, i keep wondering “how can i keep database’s password secure.?”. As you all know, i keep database’s password plain at SqlMapConfig.xml. Therefore, we need to keep our database’s password secure. One of the simplest method is to encrypting SqlMapConfig’s properties.

Im using Swing, jasypt library for basic encryption, and iBatis 2.3.4. Jasypt also need 2 additional jars, commons-lang and commons-codec, you can find them at apache’s website.

first i create a properties file, named db.properties

JDBC.Driver=1rzI2NrjkRaiwdZso6qZaI0THnqKx/wkAROxbfaCL/E=
JDBC.ConnectionURL=7EpsURgD/FFzdzuDTKYtdcT3iGPePc8uklqBweCnbCkw1wjUAKPyEA==
JDBC.Username=ciUNsgpnvS6bEkkB1F/Q8g==
JDBC.Password=c5dvo6UUKK5t633Dt6lvma0WAm5snxb+

after that, i create a singleton class to do all the Encryption-Decryption functions

package com.edw.util;

import org.jasypt.util.text.BasicTextEncryptor;

/**
 * @author edw
 */
public class BasicEncryption {

    private static final BasicEncryption basicEncryption = new BasicEncryption();
    private final String CONSTANT = "busuk";

    private BasicTextEncryptor textEncryptor = new BasicTextEncryptor();

    private BasicEncryption(){        
        textEncryptor.setPassword(CONSTANT);
    }

    public static BasicEncryption getInstance(){
        return basicEncryption;
    }

    public String encrypt(String word){
        return textEncryptor.encrypt(word);
    }

    public String decrypt(String word){
        return textEncryptor.decrypt(word);
    }

}

after that, we modified SqlMapConfig.java to put decrypted properties into SqlMapConfig.xml

package com.edw.config;

import com.edw.util.BasicEncryption;

import com.ibatis.common.resources.Resources;
import com.ibatis.sqlmap.client.SqlMapClient;
import com.ibatis.sqlmap.client.SqlMapClientBuilder;
import java.io.File;
import java.io.FileInputStream;

import java.io.IOException;
import java.io.Reader;
import java.util.Properties;

/**
 *
 * @author edw
 */
public class SqlMapConfig {

    protected static final SqlMapClient sqlMap;

    static {
        try {

            File file = new File("db.properties");
            FileInputStream fileInputStream = new FileInputStream(file);
            Properties properties = new Properties();            
            properties.load(fileInputStream);
            fileInputStream.close();

            // load encryption class
            BasicEncryption basicEncryption = BasicEncryption.getInstance();

            properties.setProperty("JDBC.Driver", basicEncryption.decrypt(properties.getProperty("JDBC.Driver")));
            properties.setProperty("JDBC.ConnectionURL", basicEncryption.decrypt(properties.getProperty("JDBC.ConnectionURL")));
            properties.setProperty("JDBC.Username", basicEncryption.decrypt(properties.getProperty("JDBC.Username")));
            properties.setProperty("JDBC.Password", basicEncryption.decrypt(properties.getProperty("JDBC.Password")));

            Reader reader = Resources.getResourceAsReader("com/edw/sqlmap/sqlmapconfig.xml");
            sqlMap = SqlMapClientBuilder.buildSqlMapClient(reader, properties);
        } catch (IOException e) {
            throw new RuntimeException("Fatal Error, ga dapet sqlmapconfignya.  Cause: " + e, e);
        } catch (Exception e){
            throw new RuntimeException("Fatal Error.  Cause: " + e, e);
        }
    }

    public static SqlMapClient getSqlMap() {
        return sqlMap;
    }
}

and we set the variable at sqlmapconfig.xml to fit decrypted properties values.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE sqlMapConfig
PUBLIC "-//ibatis.apache.org//DTD SQL Map Config 2.0//EN"
"http://ibatis.apache.org/dtd/sql-map-config-2.dtd">

<sqlMapConfig>
    <settings
        useStatementNamespaces="true"
        lazyLoadingEnabled="true"
        enhancementEnabled="true"
        maxSessions="20"
        />

    <transactionManager type="JDBC" commitRequired="false">
        <dataSource type="SIMPLE">

            <property name="SetAutoCommitAllowed" value="false"/>
            <property name="DefaultAutoCommit" value="false"/>
            
            <property name="JDBC.Driver" value="${JDBC.Driver}"/>
            <property name="JDBC.ConnectionURL" value="${JDBC.ConnectionURL}"/>
            <property name="JDBC.Username" value="${JDBC.Username}"/>
            <property name="JDBC.Password" value="${JDBC.Password}"/>
   
        </dataSource>
    </transactionManager>


    <!-- dont forget to register your sql map configs -->
    <sqlMap resource="com/edw/sqlmap/contoh.xml"/>


</sqlMapConfig>

this is my project structure
structure
structure2

this is what will happen if we submit the form
success

you can check it in the database
database

Google+