The below class is my security key provider for encryption.
public class MySecretKey {
private String key="2sfdsdf7787fgrtdfg#$%@cj5";
...
//Some Util methods goes on Here .
}
First I didn't belive that one can access the private data without a getter, but, My goodness, I am able to see the key in the console now .
And somewhere else using reflection we can see the code like below :
public static void main(String[] args) throws Exception {
Stacker myClass = new Stacker();
Field key= myClass.getClass().getDeclaredField("key");
field1.setAccessible(true);
System.out.println(key.get(myClass));
}
How can I hide my key from outside my class :( ,even private keyword also not helping me in case of Reflection.
Please give me some hint .
Thanks in advance.
setAccessible says
First, if there is a security manager, its checkPermission method is called with a
ReflectPermission("suppressAccessChecks")permission.
so you can prevent this by denying the suppressAccessChecks permission.
Really though, it'd be better to avoid relying on the JVM to preserve object inviolability. Joe-E allows for mutual-suspicion between classes within a JVM, but the JVM wasn't designed for that.
The preferred solution is to store the key in a file, and then use file system permissions to restrict access to the file. It's not a perfect solution (certainly not as convenient) but it's better than hardwiring the key in the code.
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