Can a secret be hidden in a ‘safe’ java class offering access credentials?

No, it’s not safe from other Java code. Your secret could be retrieved from an instance of Safe like this:

Field field = safe.getClass().getDeclaredField("secret");
field.setAccessible(true);
String secret = (String) field.get(safe);

Update: If you control the loading of the other Java code that you want to hide the secret from you can probably use a custom SecurityManager or ClassLoader to prevent access to it. You need to control the environment that this runs in to work though, e.g. a server you restrict access to.

Your edited question however mentions that the code can run on any desktop or device. In that case there’s really nothing you can do to protect the secret from other processes that could do just about anything. Even if you encrypt it in memory another process can just intercept the key or even the plaintext secret as its passed around.

If you don’t control the environment that you need something to be secure in then you likely need to consider a different approach. Perhaps you can avoid storing the secret in memory altogether?

Leave a Comment