Thursday, January 9, 2014

Encrypt and Decrypt AES CBC in Java


Here is an example about how to encrypt and decrypt an string using AES  CBC:

We will need:

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;


    public static void main(String[] args) throws Exception {
     
        String IV = "51515151515151515151515151515151";
        String aeskey = "78A63D60DBDFC633BD9F8ACDAC27EBBA";
        String plaintext = "It doesnt work\0\0";
        String encrypted_data = "E491C75BF68E073F34DBB7B6392B1DB2";

     
        byte[] cipher = encrypt(plaintext, aeskey, IV);
        System.out.println(DatatypeConverter.printHexBinary(cipher));
        System.out.println("---");
     
 
        byte[] encrypted_data_bytes =
                      DatatypeConverter.parseHexBinary(encrypted_data);
 
        byte[] decrypted = decrypt(encrypted_data_bytes, aeskey, IV);
        System.out.println(DatatypeConverter.printHexBinary(decrypted));
        System.out.println( new String(decrypted,"UTF-8"));
     
   
    }  
 

  public static byte[] encrypt(String plainText, String encryptionKey, String IV)  {
      byte[] i = DatatypeConverter.parseHexBinary(IV);
      byte[] a = DatatypeConverter.parseHexBinary(encryptionKey);

    Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding", "SunJCE");
    SecretKeySpec key = new SecretKeySpec(a, "AES");
    cipher.init(Cipher.ENCRYPT_MODE, key,new IvParameterSpec(i));
 
    return cipher.doFinal(plainText.getBytes("UTF-8"));
  }
   
 
    public static byte[] decrypt(byte[] cipherText, String encryptionKey, String IV) {
        byte[] i = DatatypeConverter.parseHexBinary(IV);
        byte[] a = DatatypeConverter.parseHexBinary(encryptionKey);
     
        Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
        SecretKeySpec key = new SecretKeySpec(a, "AES");
        cipher.init(Cipher.DECRYPT_MODE, key,new IvParameterSpec(i));
     
        return cipher.doFinal(cipherText);
    }

If we run the example the output will be:

run:
E491C75BF68E073F34DBB7B6392B1DB2
---
497420646F65736E7420776F726B0000
It doesnt work

Which means that the code really works :)

Hope help!


Wednesday, January 8, 2014

Convert Hex string to byte array and vice versa using Java


Hello,

A new problem today encrypting some information from mBus protocol. I need to convert Hexadecimal (hex) string to an array of bytes. Here is the solution:

Option 1:

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
       
        byte[] byteArray = hexStringToByteArray("FF");
        String again = byteArrayToHexString(byteArray);
       
        System.out.println(again );
       
    }
   
    public static byte[] hexStringToByteArray(String s) {
        int len = s.length();
        byte[] data = new byte[len / 2];
        for (int i = 0; i < len; i += 2) {
            data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
                                 + Character.digit(s.charAt(i+1), 16));
        }
       
        return data;
    }
   
    public static String byteArrayToHexString(byte[] b) {
        int len = b.length;
        String data = new String();

        for (int i = 0; i < len; i++){
            data += Integer.toHexString((b[i] >>> 4) & 0xf);
            data += Integer.toHexString(b[i] & 0xf);
        }
        return data;
    }

Option 2:



  /**
   *  Generates a hexadecimal string from an array of bytes.
   *  For example, if the array contains {0x01, 0x02, 0x3E}, 
   *  the resulting string will be "01023E".
   *
   @param bytes A Byte array
   @return A String representation
   */
  public static String toHexStringbyte[] bytes )
  {
      StringBuffer sb = new StringBufferbytes.length*);
      forint i = 0; i < bytes.length; i++ )
      {
          sb.appendtoHex(bytes[i>> 4) );
          sb.appendtoHex(bytes[i]) );
      }

      return sb.toString();
  }
  private static char toHex(int nibble)
  {
      final char[] hexDigit =
      {
          '0','1','2','3','4','5','6','7',
          '8','9','A','B','C','D','E','F'
      };
      return hexDigit[nibble & 0xF];
  }
}


Option 3:


import javax.xml.bind.DatatypeConverter;

public static String toHexString(byte[] array) {
    return DatatypeConverter.printHexBinary(array);
}

public static byte[] toByteArray(String s) {
    return DatatypeConverter.parseHexBinary(s);

}



Hope help!!