How to encrypt / decrypt using java cryptography (javax.crypto.*)

Posted on Updated on

Wandering around the web, I found no practical examples using javax.crypto libraries. Most of them are explaining in detail on how does the Java Cryptography works, what is salt, iv, password, key, etc..etc. They  are good to read but impractical, because doesn’t give a working example.
Following are the example code on how to use java crypto library:

 BRAbsCrypt.java

import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.KeySpec;
import javax.crypto.Cipher;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;
public class BRAbsCrypt {
private static final byte[] SALT = {
       (byte) 0xA9, (byte) 0x9B, (byte) 0xC8, (byte) 0x32,
       (byte) 0x56, (byte) 0x35, (byte) 0xE3, (byte) 0x03
   };
   private static final int ITERATION_COUNT = 65536;
   private static final int KEY_LENGTH = 128;
   protected SecretKey secret;

   protected Cipher getChipper(String passPhrase,int opmode, byte[] iv) throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException
   {
    SecretKeyFactory factory = SecretKeyFactory.getInstance(“PBKDF2WithHmacSHA1”);
       KeySpec spec = new PBEKeySpec(passPhrase.toCharArray(), SALT, ITERATION_COUNT, KEY_LENGTH);
       SecretKey tmp = factory.generateSecret(spec);
       SecretKey secret = new SecretKeySpec(tmp.getEncoded(), “AES”);
      Cipher echiper =  Cipher.getInstance(“AES/CBC/PKCS5Padding”);       if (iv==null)
      echiper.init(opmode, secret);
      else
      echiper.init(opmode, secret, new IvParameterSpec(iv));
      return echiper;
       }
}

BREncryptor.java

import java.security.spec.InvalidParameterSpecException;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import org.apache.commons.codec.binary.Base64;

public class BREncryptor extends BRAbsCrypt {

   private Cipher ecipher;
 
public BREncryptor(String passPhrase )   throws Exception {
ecipher = getChipper(passPhrase,Cipher.ENCRYPT_MODE,null);
 
   
}
public String generateIVbase64() throws InvalidParameterSpecException
{

return new String(Base64.encodeBase64(generateIV()));
}

public byte[] generateIV() throws InvalidParameterSpecException
{
  return ecipher.getParameters().getParameterSpec(IvParameterSpec.class).getIV();
}

public String encrypt(String encrypt) throws Exception {
    byte[] bytes = encrypt.getBytes(“UTF8”);
    byte[] encrypted = encrypt(bytes);
    return  new String(Base64.encodeBase64(encrypted));
}
public byte[] encrypt(byte[] plain) throws Exception {
    return ecipher.doFinal(plain);
}

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

BRDecryptor.java

import javax.crypto.Cipher;
import org.apache.commons.codec.binary.Base64;

public class BRDecryptor extends BRAbsCrypt {


   private Cipher dcipher;
 
   public BRDecryptor(String passPhrase,String base64iv) throws Exception {
           
byte[] iv = Base64.decodeBase64(base64iv.getBytes() );
    dcipher = getChipper(passPhrase, Cipher.DECRYPT_MODE, iv);
   }  
 
public BRDecryptor(String passPhrase,byte[] iv) throws Exception {
   dcipher = getChipper(passPhrase, Cipher.DECRYPT_MODE, iv);
}

public String decrypt(String encrypt) throws Exception {
   
byte[] bytes = Base64.decodeBase64(encrypt.getBytes());
    byte[] decrypted = decrypt(bytes);
    return new String(decrypted, “UTF8”);
}
public byte[] decrypt(byte[] encrypt) throws Exception {
    return dcipher.doFinal(encrypt);
}
public static void main(String[] args) throws Exception {
 
}
}

how to use those classes:

import org.junit.Test;
public class BRServerStaticTest {
@Test
public void testBRServerStaticEncryptDecrypt() throws Exception
{
 String message = “the quick old brown fox jumps over the lazy dog;
   String password = “how long should the password’s length”;
   String encrypted = “”;
   String decrypted =””;
  String base64iv;
   {
    BREncryptor encrypter = new BREncryptor(password);
    base64iv = encrypter.generateIVbase64();
   encrypted  = encrypter.encrypt(message);
   System.out.println(base64iv);
   }
   {
    System.out.println(base64iv);
    BRDecryptor decrypter = new BRDecryptor(password,base64iv);
    decrypted = decrypter .decrypt(encrypted);
   }
   System.out.println(“Encrypt(\”” + message + “\”, \”” + password + “\”) = \”” + encrypted + “\””);
   System.out.println(“Decrypt(\”” + encrypted + “\”, \”” + password + “\”) = \”” + decrypted + “\””);
}

}

Advertisements

2 thoughts on “How to encrypt / decrypt using java cryptography (javax.crypto.*)

    Unknown said:
    May 22, 2013 at 11:17 pm

    Good article but I'm not understanding few parts in your test code.Lets say the message is encrypted & now I want to decrypt it, so how do I decrypt it? Do I need to call BREncryptor & generate base64iv & then pass it to BRDecryptor???? For decryption, why do I need an instance of BREncryptor??Thanks!

    Andy Tanoko said:
    June 25, 2013 at 5:09 am

    the test code to demo encrypt and decrypt function, so i put them in 1 method. you don't need instance of brencryptor for decription.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s