Translate

Saturday, March 29, 2014

Encryption In Android

Andorid suppports javax.crypto package which offers different types of encryption. Here we will take a look at how AES encryption works in Android. We will write a utility class that offers both encryption and decryption. Following are the major classes we will be using to achieve the encryption and decryption


  • SecretKeySpec
  • IvParameterSpec
  • Cipher


At first we need to come up with a secret key and Initialization Vector Parameter which must be same in both the encrypt and decrypt method. Since these keys are constant we will declare them as final static.

 
private final static String key = "po#p!adfqwt#a$#2";
private final static String ivParam = "a#%^&*asksfafgha";

We can then instantiate SecretKeySpec and IvParameterSpec like this:

 
SecretKeySpec sKey = new SecretKeySpec(key.getBytes(), "AES");
IvParameterSpec ivSpec = new IvParameterSpec(ivParam.getBytes());
Finally we use Cipher class to encrypt or decrypt whatever we are interested in like this:

 
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
//For encryption
cipher.init(Cipher.ENCRYPT_MODE, sKey, ivSpec);
//For decryption
cipher.init(Cipher.DECRYPT_MODE, sKey, ivSpec);
byte[] encrptedBytes = cipher.doFinal("somePassword".getBytes());
Here is the entire class:

 

import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

import javax.crypto.BadPaddingException; import javax.crypto.Cipher; import javax.crypto.IllegalBlockSizeException; import javax.crypto.NoSuchPaddingException; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec;

public class Encryption { private final static String key = "po#p!adfqwt#a$#2"; private final static String ivParam = "a#%^&*asksfafgha";

public String encrypt(String word) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException { SecretKeySpec sKey = new SecretKeySpec(key.getBytes(), "AES"); IvParameterSpec ivSpec = new IvParameterSpec(ivParam.getBytes()); Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE, sKey, ivSpec); byte[] encryptedBytes = cipher.doFinal(word.getBytes()); return new String(encryptedBytes); }
public String decrypt(String word) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException { SecretKeySpec sKey = new SecretKeySpec(key.getBytes(), "AES"); IvParameterSpec ivSpec = new IvParameterSpec(ivParam.getBytes()); Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); cipher.init(Cipher.DECRYPT_MODE, sKey, ivSpec); byte[] decryptedBytes = cipher.doFinal(word.getBytes()); return new String(decryptedBytes); } }



No comments:

Post a Comment