Translate

Sunday, April 27, 2014

Reading from a file in Android

There are couple ways to read from a file in android. The file can be included as part of the Android Project in to the res directory Or the file can also be read from SD Card or internal storage. I will share couple ways to read the content of a file.

Method 1: Reading from res directory
Lets say we have a file called test.txt. The first thing we need to do is create a new folder called raw within the res directory and store the file there. So out file location will look like this

res/raw/test.txt

The following code snippet will read the content of this file into a String.
 
InputStream inputStream = this.getResources().openRawResource(
    R.raw.test);
  ByteArrayOutputStream bos = new ByteArrayOutputStream();
  
 
   int i = 0;
   try {
    while((i = inputStream.read())!=-1) {
     bos.write(i);
    }
    bos.close();
    inputStream.close();
   } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
  
  String content = bos.toString();
  Log.i("File Content is", content);



Method 2: Reading from External Storage/SD Card
say we have a file called test.txt in the root of sdcard. The following code snippet will read the file into a String object.
 
  File file = new File(Environment.getExternalStorageDirectory() + "/test.txt");
  try {
   FileReader fr = new FileReader(file);
   BufferedReader br = new BufferedReader(fr);
   StringBuffer sb = new StringBuffer();
   String line = "";
   while((line=br.readLine())!=null) {
    sb.append(line);
   }
   String content = sb.toString();
   Log.i("File Content is", content);
   br.close();
   fr.close();
  } catch (FileNotFoundException e) {
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  }

This method requires Read External Storage permission declared in the manifest file
 
android.permission.READ_EXTERNAL_STORAGE


Let me know if you have any question on the comments...


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); } }