Search This Blog

Friday, January 9, 2015

Encrypt the password using algorithm and Decrypt it using one secret key

Its necessary to encrypt the user data that is not to be revealed by any third party user which can be harmful to the user.

There may be so many encryption and decryption techniques available for encrypt and decrypt the data. But I am posting one of them here.

Firstly, Copy following class into your code. And import all the classes.

 public class Encryption {
  private static final String TAG = "Encryption";
  private String mCharsetName = "UTF8";
  private int mBase64Mode = Base64.DEFAULT;
  private String mSecretKeyType = "PBKDF2WithHmacSHA1";
  private String mSalt = "some_salt";
  private int mKeyLength = 128;
  private int mIterationCount = 65536;
  private String mAlgorithm = "AES";

  public String encrypt(String key, String data) {
         if (key == null || data == null)
             return null;
         try {
            SecretKey secretKey = getSecretKey(hashTheKey(key));
            byte[] dataBytes = data.getBytes(mCharsetName);
            Cipher cipher = Cipher.getInstance(mAlgorithm);
            cipher.init(Cipher.ENCRYPT_MODE, secretKey);
            return Base64.encodeToString(cipher.doFinal(dataBytes), mBase64Mode);
        } catch (Exception e) {
            Log.e(TAG, e.toString());
            return null;
        }
   }
   public String decrypt(String key, String data) {
           if (key == null || data == null)
               return null;
           try {
               byte[] dataBytes = Base64.decode(data, mBase64Mode);
               SecretKey secretKey = getSecretKey(hashTheKey(key));
               Cipher cipher = Cipher.getInstance(mAlgorithm);
               cipher.init(Cipher.DECRYPT_MODE, secretKey);
               byte[] dataBytesDecrypted = (cipher.doFinal(dataBytes));
               return new String(dataBytesDecrypted);
            } catch (Exception e) {
               Log.e(TAG, e.toString());
               return null;
            }
   }

   private SecretKey getSecretKey(char[] key) throws NoSuchAlgorithmException,
               UnsupportedEncodingException, InvalidKeySpecException {
          SecretKeyFactory factory;
          factory = SecretKeyFactory.getInstance(mSecretKeyType);
          KeySpec spec = new PBEKeySpec(key, mSalt.getBytes(mCharsetName),
                          mIterationCount, mKeyLength);
          SecretKey tmp = factory.generateSecret(spec);
          return new SecretKeySpec(tmp.getEncoded(), mAlgorithm);
   }

     private char[] hashTheKey(String key) throws UnsupportedEncodingException,
                 NoSuchAlgorithmException {
           MessageDigest md = MessageDigest.getInstance("SHA1");
           md.update(key.getBytes(mCharsetName));
           return Base64.encodeToString(md.digest(), Base64.NO_PADDING)
                            .toCharArray();
     }
}



Using this class please create an object of it. Please set One secret key by which you want to encrypt the password.

public static String secretKey = "YourSecreteKey";


Encryption encryption = new Encryption();
String encryptedPassword = encryption
.encrypt(
secretKey 
, masterPassword
.getText().toString());


using this secretKey you will get the encrypted data.

Saturday, January 3, 2015

Implement Message Digest algorithm

SHA1 message digest for securing your string for storing into database.

Firstly create a method called sha1(String password). Here pass the password as a string as a parameter.

String sha1(String input) throws NoSuchAlgorithmException {
MessageDigest mDigest = MessageDigest.getInstance("SHA1");
byte[] result = mDigest.digest(input.getBytes());
StringBuffer sb = new StringBuffer();
for (int i = 0; i < result.length; i++) {
sb.append(Integer.toString((result[i] & 0xff) + 0x100, 16)
.substring(1));
}
return sb.toString();
}

Now just get the input from user and store it using this method into database

String shapassword = sha1(masterPassword.getText().toString().trim());

Tuesday, October 7, 2014

Putting the divider in ListView

Here is the code for the divider in android list view.

int[] colors = {0, 0xFFFF0000, 0};
myListview.setDivider(new GradientDrawable(Orientation.RIGHT_LEFT, colors));
myListview.setDividerHeight(1);

This will brought into new gradient styled divider.

Saturday, November 23, 2013

Get the Original file path From the Uri in the OnActivity Result

First of all pass the Intent to pick the image from the external storage.. or gelllary

Intent intent = new Intent(Intent.ACTION_PICK, 
      Images.Media.EXTERNAL_CONTENT_URI);
    startActivityForResult(intent, 0);


OnActivityResult write the following code snippet

@Override
 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  super.onActivityResult(requestCode, resultCode, data);
  
  if(resultCode == RESULT_OK){
   
   image.setImageBitmap(null);
   
   //Uri return from external activity
   orgUri = data.getData();
   text1.setText("Returned Uri: " + orgUri.toString() + "\n");
   
   //path converted from Uri
   convertedPath = getRealPathFromURI(orgUri);
   text2.setText("Real Path: " + convertedPath + "\n");
   
   //Uri convert back again from path
   uriFromPath = Uri.fromFile(new File(convertedPath));
   text3.setText("Back Uri: " + uriFromPath.toString() + "\n");
  }
  
 }

Getting the real path of the Image using the Uri returned in OnActivityResult...

public String getRealPathFromURI(Uri contentUri) {
  String[] proj = { MediaStore.Images.Media.DATA };
  
  //This method was deprecated in API level 11
  //Cursor cursor = managedQuery(contentUri, proj, null, null, null);
  
  CursorLoader cursorLoader = new CursorLoader(
            this, 
            contentUri, proj, null, null, null);        
  Cursor cursor = cursorLoader.loadInBackground();
  
  int column_index = 
    cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
  cursor.moveToFirst();
  return cursor.getString(column_index); 
 }

List of Files in the Directory with specified type

Pass the File Directory in the method and extension if you want to get the files with different file extensions.

 private File[] getJpgFiles(File f){

  File[] files = f.listFiles(new FilenameFilter(){

   @Override
   public boolean accept(File dir, String filename) {
    return filename.toLowerCase().endsWith(".jpg");
   }});
  
  return files;
 }

Delete Directory with its all the inner file and Directories

This is the simple method to remove all the files and folders from the path in the SDcard.

void DeleteRecursive(File fileOrDirectory) {
if (fileOrDirectory.isDirectory())
for (File child : fileOrDirectory.listFiles())
DeleteRecursive(child);

fileOrDirectory.delete();
}

Unzipping the zip file with the location using ZipInputStream and ZIpEntry

Make a File with the name Decompress.java and add the following code snippet in it.

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

import android.util.Log;

/**
 * 
 * @author jon
 */
public class Decompress {
private String _zipFile;
private String _location;

public Decompress(String zipFile, String location) {
_zipFile = zipFile;
_location = location;

_dirChecker("");
}

public void unzip() {
try {
FileInputStream fin = new FileInputStream(_zipFile);
ZipInputStream zin = new ZipInputStream(fin);
ZipEntry ze = null;
while ((ze = zin.getNextEntry()) != null) {
Log.v("Decompress", "Unzipping " + ze.getName());

if (ze.isDirectory()) {
_dirChecker(ze.getName());
} else {
FileOutputStream fout = new FileOutputStream(_location
+ ze.getName());
for (int c = zin.read(); c != -1; c = zin.read()) {
fout.write(c);
}

zin.closeEntry();
fout.close();
}

}
zin.close();
deleteDir(_zipFile);
} catch (Exception e) {
Log.e("Decompress", "unzip", e);
}

}

private void _dirChecker(String dir) {
File f = new File(_location + dir);

if (!f.isDirectory()) {
f.mkdirs();
}
}

private void deleteDir(String dir) {
// TODO Auto-generated method stub
File f = new File(dir);
// Util.iLog("delete dir :" + dir);
if (f.exists()) {
f.delete();
}
}
}


Now call these class with the zip file location and unzip location with the following code snippet

Decompress d = new Decompress(zipfileloc, Unziploc);
d.unzip();