Hiding my security key from java reflection

风格不统一 提交于 2020-01-02 08:38:14

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!