Monday, 24 October 2016

AES Encryption in Android



MainActivity.java 

package com.example.encryptionexample;

import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;

public class MainActivity extends ActionBarActivity {

    String seedValue = "This Is MySecure";
   
    @Override
    protected void onCreate(Bundle savedInstanceState) {
           super.onCreate(savedInstanceState);
              String normalText = "RAJESH";
           String normalTextEnc;
                  try {
                 AESCrypt a=new AESCrypt(seedValue);
                          TextView txe = new TextView(this);
                          txe.setTextSize(14);
                          txe.setText("Normal Text ::"+normalText +" \n Encrypted Value :: "+ a.encrypt(normalText) +" \n Decrypted value :: "+a.decrypt(a.encrypt(normalText)));
                          setContentView(txe);
                  } catch (Exception e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                  }
       

       
    }
}

AESCrypt.java

package com.example.encryptionexample;

import java.security.MessageDigest;
import java.security.SecureRandom;
import java.security.spec.AlgorithmParameterSpec;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import android.util.Base64;

public class AESCrypt {

private final Cipher cipher;
private final SecretKeySpec key;
private AlgorithmParameterSpec spec;


public AESCrypt(String password) throws Exception
{
   // hash password with SHA-256 and crop the output to 128-bit for key
   MessageDigest digest = MessageDigest.getInstance("SHA-256");
   digest.update(password.getBytes("UTF-8"));
   byte[] keyBytes = new byte[32];
   System.arraycopy(digest.digest(), 0, keyBytes, 0, keyBytes.length);

   cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
   key = new SecretKeySpec(keyBytes, "AES");
   spec = getIV();
}       

public AlgorithmParameterSpec getIV()
{
   byte[] iv = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, };
   IvParameterSpec ivParameterSpec;
   ivParameterSpec = new IvParameterSpec(iv);

   return ivParameterSpec;
}

public String encrypt(String plainText) throws Exception
{
   cipher.init(Cipher.ENCRYPT_MODE, key, spec);
   byte[] encrypted = cipher.doFinal(plainText.getBytes("UTF-8"));
   String encryptedText = new String(Base64.encode(encrypted, Base64.DEFAULT), "UTF-8");

   return encryptedText;
}

public String decrypt(String cryptedText) throws Exception
{
   cipher.init(Cipher.DECRYPT_MODE, key, spec);
   byte[] bytes = Base64.decode(cryptedText, Base64.DEFAULT);
   byte[] decrypted = cipher.doFinal(bytes);
   String decryptedText = new String(decrypted, "UTF-8");

   return decryptedText;
}
}

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="com.example.encryptionexample.MainActivity">
  <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/hello_world" />
  </RelativeLayout>

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.encryptionexample"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="21" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>



No comments:

Post a Comment