Sunday, June 16, 2013

Android: Implementation of Cryptography using AES (128 bit) Technique.


 What is Cryptography?

The art of protecting information by transforming it into an unreadable format, called cipher text using a secret key. Only those who possess a secret key can decipher the message into plaintext.

  • The process of converting the "plaintext"  into "ciphertext" is called Encryption.
  • The process of converting the "ciphertext" into "plaintext" is called Decryption.

Let see the cryptography mechanism in android using AES (Advanced Encryption Standard) Technique.

AES is based on a design principle known as a substitution-permutation network. AES has fixed block size of 128 bit. i.e, the ciphertext will be the  length of 16 character always.

The algorithm described by AES is a symmetric-key algorithm, meaning the same key is used for both encrypting and decrypting the data.

The key size used for an AES cipher specifies the number of repetitions of transformation rounds that convert the input, called the plaintext, into the final output, called the ciphertext. The number of cycles of repetition are as follows:
  • 10 cycles of repetition for 128-bit keys.
  • 12 cycles of repetition for 192-bit keys.
  • 14 cycles of repetition for 256-bit keys.
Cryptography Implementation Class:

package com.hopabit.cryptography;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

import android.util.Base64;

/*
 * Cryptography using AES (Advanced Encryption Standard) 128 bit AES Mechanisam
 * (10 cycles of repetition for 128-bit keys.)
 * 
 */
public class SecurityUtils {

 // 128 bit Key (length 16 character) -- (10 cycles of repetition for 128-bit keys)
 static String KEY = "sbal21duolcat129";
 // 192 bit key (length 24 character) -- (12 cycles of repetition for 192-bit keys)
 static String KEY1 = "sbal21duolcat129sbal21du";
 // 256 bit Key (length 32 character) -- (14 cycles of repetition for 256-bit keys)
 static String KEY2 = "sbal21duolcat129abc123efglcat143";

 /*
  * Encryption method using ECB (Electronic Code Book) mode
  * 
  * @param Plain text
  * 
  * It will return cipher text as string value
  */

 public static String encryptECB(String password) {

  byte[] raw = KEY.getBytes();
  SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
  try {
   Cipher cipher = Cipher.getInstance("AES");
   Cipher.getInstance("AES/ECB/PKCS7Padding");
   cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
   byte[] encrypted;
   encrypted = cipher.doFinal(password.getBytes());
   return new String(Base64.encode(encrypted, Base64.DEFAULT));
  } catch (Exception e) {
   e.printStackTrace();
  }
  return null;
 }

 /*
  * Decryption method using ECB (Electronic Code Book) mode
  * 
  * @param Ciper text
  * 
  * It will return plain text as string value
  */

 public static String decryptECB(String ciphertext) {

  byte[] raw = KEY.getBytes();
  SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
  try {
   Cipher decipherd = Cipher.getInstance("AES");
   Cipher.getInstance("AES/ECB/PKCS7Padding");
   decipherd.init(Cipher.DECRYPT_MODE, skeySpec);
   // Decode the cipher text using Base64 first
   byte[] decoded_cipher = Base64.decode(ciphertext, Base64.DEFAULT);
   byte[] decrypted = decipherd.doFinal(decoded_cipher);
   return new String(decrypted);

  } catch (Exception e) {
   e.printStackTrace();
  }
  return null;
 }

}

In your activity by calling this method you can get encrypted and decrypted values.

// encryption
String encrypt = SecurityUtils.encryptECB("hopabit123");

// decryption
String decrypt = SecurityUtils.decryptECB("uPtImPC4zTOr4DJbWnzyXg==");

Happy coding :-)

Some useful online tools:



Saturday, June 15, 2013

Android: Chat head View like in Facebook Messenger App



In the recent update of the  Facebook Messenger App, you can able to see this new view called "Chat heads".

The logic behind this Chat heads is just adding a view in Window.The awesome part is it will draw small window with chat heads on top of other applications too.


Let see the implementation part now.

 Chat head service class:


package com.hopabit.chathead.services;

import android.app.Service;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.os.IBinder;
import android.view.Gravity;
import android.view.WindowManager;
import android.widget.ImageView;

import com.cloudinfy.chathead.R;

public class ChatHeadService extends Service {

 private WindowManager windowManager;
 private ImageView chatHead;

 @Override
 public IBinder onBind(Intent intent) {
  // TODO Auto-generated method stub
  return null;
 }

 @Override
 public void onCreate() {
  super.onCreate();

  windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
  chatHead = new ImageView(this);
  chatHead.setImageResource(R.drawable.chat_head);

  final WindowManager.LayoutParams params = new WindowManager.LayoutParams(
    WindowManager.LayoutParams.WRAP_CONTENT,
    WindowManager.LayoutParams.WRAP_CONTENT,
    WindowManager.LayoutParams.TYPE_PHONE,
    WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
    PixelFormat.TRANSLUCENT);

  params.gravity = Gravity.TOP | Gravity.LEFT;
  params.x = 0;
  params.y = 100;

  windowManager.addView(chatHead, params);

  
 }

 @Override
 public void onDestroy() {
  // TODO Auto-generated method stub
  super.onDestroy();
  if (chatHead != null)
   windowManager.removeView(chatHead);
 }
}

Then we need to start the ChatHeadService class in our activity:



startService(new Intent(context, ChatHeadService.class));  

Also, we can add the action/event in that view.Refer the below code for drag event.



chatHead.setOnTouchListener(new View.OnTouchListener() {
   private int initialX;
   private int initialY;
   private float initialTouchX;
   private float initialTouchY;

   @Override
   public boolean onTouch(View v, MotionEvent event) {
    switch (event.getAction()) {
    case MotionEvent.ACTION_DOWN:
     initialX = params.x;
     initialY = params.y;
     initialTouchX = event.getRawX();
     initialTouchY = event.getRawY();
     return true;
    case MotionEvent.ACTION_UP:
     return true;
    case MotionEvent.ACTION_MOVE:
     params.x = initialX
       + (int) (event.getRawX() - initialTouchX);
     params.y = initialY
       + (int) (event.getRawY() - initialTouchY);
     windowManager.updateViewLayout(chatHead, params);
     return true;
    }
    return false;
   }
  });

Don't forget to include the following permission in the manifest file:

SYSTEM_ALERT_WINDOW

 <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>

Happy coding :)