Encryption/Decryption in Android

Encrytion is translation of data into a secret code. Encryption is the best way to achieve data security. To read an encrypted file, you must have access to a password or secret key that enables you to decrypt it. Unencrypted data is called plain text  and encrypted data is called cipher text.

Create Android Project with name as "EncryDemo" with package name "com.etr.encrydemo". Create Activity with name as "MainActivity". This is the code for MainActivity.

You can download source code here.

package com.etr.encrydemo;

import java.io.IOException;
import java.security.GeneralSecurityException;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.PBEParameterSpec;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends Activity {
EditText value, encryValue;
Button encry, decry;

@Override
protected void onCreate(Bundle savedInstanceState) {
try {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

value = (EditText) findViewById(R.id.editText1);
encryValue = (EditText) findViewById(R.id.editText2);
encry = (Button) findViewById(R.id.button1);
decry = (Button) findViewById(R.id.button2);

encry.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View arg0) {
try {
encryValue.setText(FileEncryptor.encryptFile(value
.getText().toString(), "tamilnadu"));
value.setText("");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (GeneralSecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});

decry.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
try {
value.setText(FileEncryptor.decryptFile(encryValue
.getText().toString(), "tamilnadu"));
encryValue.setText("");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (GeneralSecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});

} catch (Exception e) {
Log.d("Exception ", Log.getStackTraceString(e));
}
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}

static class FileEncryptor {

private static final byte[] salt = { (byte) 0x43, (byte) 0x76,
(byte) 0x95, (byte) 0xc7, (byte) 0x5b, (byte) 0xd7,
(byte) 0x45, (byte) 0x17 };

private static Cipher makeCipher(String pass, Boolean decryptMode)
throws GeneralSecurityException {

PBEKeySpec keySpec = new PBEKeySpec(pass.toCharArray());
SecretKeyFactory keyFactory = SecretKeyFactory
.getInstance("PBEWithMD5AndDES");
SecretKey key = keyFactory.generateSecret(keySpec);

PBEParameterSpec pbeParamSpec = new PBEParameterSpec(salt, 42);

Cipher cipher = Cipher.getInstance("PBEWithMD5AndDES");

if (decryptMode) {
cipher.init(Cipher.ENCRYPT_MODE, key, pbeParamSpec);
} else {
cipher.init(Cipher.DECRYPT_MODE, key, pbeParamSpec);
}

return cipher;
}

public static String encryptFile(String value, String pass)
throws IOException, GeneralSecurityException {
byte[] encData;

Cipher cipher = FileEncryptor.makeCipher(pass, true);

encData = cipher.doFinal(value.getBytes());

return android.util.Base64.encodeToString(encData, 0);
}

public static String decryptFile(String value, String pass)
throws GeneralSecurityException, IOException {
byte[] decData;

Cipher cipher = FileEncryptor.makeCipher(pass, false);

decData = cipher.doFinal(android.util.Base64.decode(value, 0));

return new String(decData);
}

}

}

This is code for "activity_main.xml"

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_centerVertical="true"
        android:layout_marginLeft="22dp"
        android:text="Encrytion" />

    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_centerVertical="true"
        android:layout_marginRight="30dp"
        android:text="Decrytion" />

    <EditText
        android:id="@+id/editText1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="58dp"
        android:ems="10"
        android:inputType="text" />

    <EditText
        android:id="@+id/editText2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_above="@+id/button1"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="28dp"
        android:ems="10"
        android:inputType="text" >

        <requestFocus />
    </EditText>

</RelativeLayout>

Comments

Popular posts from this blog

SQLiteDatabase With Multiple Tables

Programmatically turn ON/OFF WiFi on Android device

Android Service and IntentService