This example demonstrates how you can do object hacking in Java using the Reflection API. Hacking by reflection is possible through setAccessible() method provided in Reflection API. Most of the Java object hacking techniques utilize this to Hack objects.
In a typical Java application you will not be able to access a private variable of a class outside the class. If you use Reflection then you can access all private fields of a Java class. Here I am taking an example of password field.
SecureData class contains a private password field which does not provide any access to outside world. Code in main method of SecuredDataHack class demonstrates how we can easily access what is inside the password field. You can clearly see that its not only reading the fields but also setting it to new value, which could be disastrous.
package hacking; import java.lang.reflect.Field; public class SecuredDataHack { public static void main(String[] args) throws Exception { SecureData s = SecureData.class.newInstance(); Field f[] = s.getClass().getDeclaredFields(); f[0].setAccessible(true); Object pass = new Object(); pass = f[0].get(s); System.out.println("Here is your " + f[0].getName() + " : " + pass ); f[0].set(s, "NewPassword"); pass = f[0].get(s); System.out.println("Here is new " + f[0].getName() + " : " + pass ); } }
This is my class which contains a private attribute called password. I don’t want to allow anyone to have access of it so I did not provide any get or set method for it. Lets see if Reflection can Hack it?
package hacking; public class SecureData { private String password = "MySecretPassword"; }
Below is the output of this program
Here is your password : MySecretPassword Here is new password : NewPassword