Wednesday, October 23, 2013

Android Example for encrypt and decrypt using AES Algorithms

Android Example for encrypt and decrypt using AES Algorithms

Below the example for how to encrypt and decrypt the values Using AES Algorithms. Make our data store in  secure.

Screen Shot



AESHelper class

package com.example.encription;

import java.security.SecureRandom;

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

public class AESHelper {

        public static String encrypt(String seed, String cleartext) throws Exception {
                byte[] rawKey = getRawKey(seed.getBytes());
                byte[] result = encrypt(rawKey, cleartext.getBytes());
                return toHex(result);
        }
       
        public static String decrypt(String seed, String encrypted) throws Exception {
                byte[] rawKey = getRawKey(seed.getBytes());
                byte[] enc = toByte(encrypted);
                byte[] result = decrypt(rawKey, enc);
                return new String(result);
        }

        private static byte[] getRawKey(byte[] seed) throws Exception {
                KeyGenerator kgen = KeyGenerator.getInstance("AES");
                SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
                sr.setSeed(seed);
            kgen.init(128, sr); // 192 and 256 bits may not be available
            SecretKey skey = kgen.generateKey();
            byte[] raw = skey.getEncoded();
            return raw;
        }

       
        private static byte[] encrypt(byte[] raw, byte[] clear) throws Exception {
            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
                Cipher cipher = Cipher.getInstance("AES");
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
            byte[] encrypted = cipher.doFinal(clear);
                return encrypted;
        }

        private static byte[] decrypt(byte[] raw, byte[] encrypted) throws Exception {
            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
                Cipher cipher = Cipher.getInstance("AES");
            cipher.init(Cipher.DECRYPT_MODE, skeySpec);
            byte[] decrypted = cipher.doFinal(encrypted);
                return decrypted;
        }

        public static String toHex(String txt) {
                return toHex(txt.getBytes());
        }
        public static String fromHex(String hex) {
                return new String(toByte(hex));
        }
       
        public static byte[] toByte(String hexString) {
                int len = hexString.length()/2;
                byte[] result = new byte[len];
                for (int i = 0; i < len; i++)
                        result[i] = Integer.valueOf(hexString.substring(2*i, 2*i+2), 16).byteValue();
                return result;
        }

        public static String toHex(byte[] buf) {
                if (buf == null)
                        return "";
                StringBuffer result = new StringBuffer(2*buf.length);
                for (int i = 0; i < buf.length; i++) {
                        appendHex(result, buf[i]);
                }
                return result.toString();
        }
        private final static String HEX = "0123456789ABCDEF";
        private static void appendHex(StringBuffer sb, byte b) {
                sb.append(HEX.charAt((b>>4)&0x0f)).append(HEX.charAt(b&0x0f));
        }
       

}

Activity Source Code

package com.example.encription;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.TextView;
import android.widget.Toast;


/***
 *
 * @author vijay
 *
 */
public class MainActivity extends Activity {

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

           
       }

      
}

Wednesday, October 9, 2013

Android Load Images from SDCARD Specific Folder in Gallery view

Android Load Images from SDCARD Specific Folder in Gallery view 

Below the example for how to load images from SDCARD specific folder.

Fetch the images from sdcard specific folder then load into Gallerry view and zoom the images.

Screen Shot
Load images to Gallery view

Zoom Image-selected image
Source Code

Activity Source Code
package com.imageload.vjblog;

import java.io.File;
import java.text.DecimalFormat;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.AdapterView;

import android.widget.ImageView;

import android.widget.Gallery;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

/***
 *
 * @author vijay_kumar
 *
 */

public class MainActivity extends Activity {

       private String[] FilePathStrings;
       private String[] FileNameStrings;
       private File[] listFile;
       Gallery gallerry;
       GridViewAdapter adapter;
       File file;

       @Override
       public void onCreate(Bundle savedInstanceState) {
              super.onCreate(savedInstanceState);
              setContentView(R.layout.gridview_main);

              // Check for SD Card
              if (!Environment.getExternalStorageState().equals(
                           Environment.MEDIA_MOUNTED)) {
                     Toast.makeText(this, "Error! No SDCARD Found!", Toast.LENGTH_LONG)
                                  .show();
              } else {
                     file = new File(Environment.getExternalStorageDirectory()
                                  + File.separator + "here_your_specific_folder");
                     file.mkdirs();
              }

              if (file.isDirectory()) {
                     listFile = file.listFiles();
                     FilePathStrings = new String[listFile.length];
                     FileNameStrings = new String[listFile.length];

                     for (int i = 0; i < listFile.length; i++) {
                           FilePathStrings[i] = listFile[i].getAbsolutePath();
                           FileNameStrings[i] = listFile[i].getName();
                     }
              }

              gallerry = (Gallery) findViewById(R.id.gridview);
              adapter = new GridViewAdapter(this, FilePathStrings, FileNameStrings);
              gallerry.setSpacing(2);
              gallerry.setAdapter(adapter);

              gallerry.setOnItemClickListener(new OnItemClickListener() {

                     @Override
                     public void onItemClick(AdapterView<?> parent, View view,
                                  int position, long id) {

                           zoomImage(position);
                     }

              });
       }
      
       private void zoomImage(int position) {
              final Dialog dialog = new Dialog(MainActivity.this);
              dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
              dialog.getWindow().setBackgroundDrawableResource(
                           android.R.color.transparent);
              dialog.setContentView(R.layout.image_zoomdialog);
              ImageView imageview = (ImageView) dialog.findViewById(R.id.imageView1);
              Bitmap bmp = BitmapFactory.decodeFile(FilePathStrings[position]);
              imageview.setImageBitmap(bmp);
              dialog.show();
             
       }

}



Adapter Class

package com.imageload.vjblog;


import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.TextView;

public class GridViewAdapter extends BaseAdapter {

       // Declare variables
       private Activity activity;
       private String[] filepath;
       private String[] filename;

       private static LayoutInflater inflater = null;

       public GridViewAdapter(Activity a, String[] fpath, String[] fname) {
              activity = a;
              filepath = fpath;
              filename = fname;
              inflater = (LayoutInflater) activity
                           .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

       }

       public int getCount() {
              return filepath.length;

       }

       public Object getItem(int position) {
              return position;
       }

       public long getItemId(int position) {
              return position;
       }

       public View getView(int position, View convertView, ViewGroup parent) {
             
                // TODO Auto-generated method stub
        ImageView i = new ImageView(activity);
       Bitmap bmp = BitmapFactory.decodeFile(filepath[position]);
      //  i.setImageResource(mImageIds[position]);
        i.setLayoutParams(new Gallery.LayoutParams(200, 200));
        i.setScaleType(ImageView.ScaleType.FIT_XY);
        i.setImageBitmap(bmp);
              return i;
       }
}



Layout

gridview_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:padding="5dip" >

    <Gallery
        android:id="@+id/gridview"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:columnWidth="90dp"
        android:numColumns="auto_fit"
        android:stretchMode="columnWidth" />

</RelativeLayout>


image_zoomdialog.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
         />

</LinearLayout>


Add permission in Manifest


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

Check out this may be help you

Related Posts Plugin for WordPress, Blogger...