Consider this sample class,
class TargetClass {
private static String SENSITIVE_DATA = "sw0rdfish";
private static String getSensitiveData() {
return SENSITIVE_DATA;
}
}
When I do this,
import java.lang.reflect.Method;
public class ClassPiercing {
public static void main(String... args) throws Exception {
Class targetClass = Class.forName("TargetClass");
Method[] methods = targetClass.getDeclaredMethods();
methods[0].setAccessible(true);
String sensitiveData = (String)methods[0].invoke(null, null);
System.out.println("Sensitive Data: " + sensitiveData);
}
}
The output is,
Sensitive Data: sw0rdfish
This is dangerous. How do I prevent this from happening?
Well, use a SecurityManager.
http://java.sun.com/javase/6/docs/api/java/lang/SecurityManager.html
http://java.sun.com/javase/6/docs/technotes/guides/security/permissions.html#ReflectPermission
disabling ReflectPermission should do the trick.
The point of access control is not to prevent someone from hacking in to your code; It's a matter of signalling intend to other programmers (eg. api design). If you don't trust the other program, you should run use different measures. For example, you could encrypt the data somehow.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With