Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hiding my security key from java reflection

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.

like image 335
Suresh Atta Avatar asked Nov 25 '25 19:11

Suresh Atta


2 Answers

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.

like image 73
Mike Samuel Avatar answered Nov 28 '25 09:11

Mike Samuel


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.

like image 34
jdigital Avatar answered Nov 28 '25 07:11

jdigital