问题
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.
回答1:
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.
回答2:
All the strings defined in a Java class can be easily inspected by opening the class file in a hexadecimal editor, they're not, by any means, hidden. not to mention that they can be retrieved programatically using reflection, as you just discovered.
The mechanism you're using for "hiding" a private key is broken, and utterly flawed. You should instead store the key in an external file, for example a serialized, encrypted key store, protected by other means - for example, a password or another key stored elsewhere.
回答3:
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.
回答4:
Easy,
Make this class non-instantiatable
How?
Make a private constructor and make your key field static
So your class will look like this
public class MySecretKey {
public static String key="2sfdsdf7787fgrtdfg#$%@cj5";
private MySecretKey(){} //Private constructor
//No Util methods will go here.
}
来源:https://stackoverflow.com/questions/14903318/hiding-my-security-key-from-java-reflection