Pages

Thursday, 9 May 2013

Is private encapsulation always secure?


Suppose you make a method private in Java, experience tells us this is bread and butter stuff and only methods inside this class can access the private methods.  However, in the following example I'll show how setting methods as private isn't always safe.

From here, we can see if we had an instantiated User object, we could just call user.getFirstName(); However - what if we wanted to get the password?  We can use reflection to access this private method.

This is where the Method object in the Java.lang.reflect package is useful.  If I was to reflect this method back into an object, I'm able to set the accessibility of this object.

The accessibility method call is important as it will turn off any encapsulation checks on this method invocation.  We can then simply invoke this method as shown below to result in the password being printed out.


This is one of the many reasons why storing your passwords in plain text in a compiled object, even if you make the methods private, is dangerous.

No comments:

Post a Comment