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

后端 未结 12 1731
北荒
北荒 2020-12-03 09:04

This is a brainstorming question about what\'s possible in Java (or not). I want to know if it is possible to hide a secret within a class and prevent anymore from accessing

12条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-03 09:29

    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?

提交回复
热议问题