Wednesday 27 June 2012

Java - Is is possible to access private values through reflection?

import java.lang.reflect.Field;

class A {
    private int i = 10;
    private int j = 10;
   
    A(int i,int j) {
        this.i=i;
        this.j=j;
    }
    private static String ProtectData() {
        return "Protected Password";
    }
    private static String SecureData() {
        return "Secure Password";
    }
}

Non- Generic way of access the private variable

==================================
public class Test {

    /**
     * @param args
     */
    public static void main(String[] args) throws Exception {
        Object cl = new A(20,36);
        java.lang.reflect.Method m = cl.getClass().getDeclaredMethod("ProtectData",null);
        java.lang.reflect.Field f = cl.getClass().getDeclaredField("i");
       
        m.setAccessible(true);
        f.setAccessible(true);
        f.setInt(cl, 45);
        String pass = (String) m.invoke(null, null);
        int passed = (int) f.getInt(cl);
        System.out.println("Protected data:" + pass);
        System.out.println("Protected data:" + passed);

    }
}

 
Generic way of access the private variable
==============================
 
class Tests {

    public static void main(String[] args) throws Exception {
        Object cl = new A(20,36);
        java.lang.reflect.Method[] m = cl.getClass().getDeclaredMethods();
        java.lang.reflect.Field[] f = cl.getClass().getDeclaredFields();
               
        m[1].setAccessible(true);
        f[0].setAccessible(true);
       
        f[0].setInt(cl, 30);
       
        String pass = (String) m[1].invoke(null, null);
        int passed = (int) f[0].getInt(cl);
        System.out.println("secure data:" + pass);
        System.out.println("secure data:" + passed);

    }
}


We protect our object form this Hacking Technique?
To call setAccessible when security is enabled, you must have the suppressAccessChecks permission. By default, code that is in the core API or the extensions directory will have the suppressAccessChecks permission and be able to perform services such as serializing an object's private state.
/* grant the klib library AllPermission */
grant codebase "file:${klib.home}/j2ee/home/klib.jar" {
  permission java.lang.reflect.ReflectPermission "suppressAccessChecks";
};

==========================

Just spend you precious minute to analysis the following code and predict the output
public class Puzzle {
 
    public static void main(String[] args) throws Exception {
      String String;
      String = new String("Welcome to our Puzzle");
      System.out.println("String "+String);
    }
}