确保方法只能通过所选方法

时间:2017-11-05 08:48:01

标签: java

我需要确保来自类的方法仅由来自不同包的选定方法执行。

package myApp.security;
public class SecurityStuff{
    public static final SecurityStuff security = new SecurityStuff();
    public KeyStore getKeyStore(){
        //if invoked by MySock.getTLSServerSocket()
        return keyStore;
        //if not, should return null
    }
}

package myApp.socks;
public class MySock{
    public void getTLSServerSocket(){
        KeyStore keyStore = SecurityStuff.security.getKeyStore();
    }
}

通过上面的2个课程,我如何确保SecurityStuff.getKeyStore()返回KeyStore iff来自课程&我允许的方法?

请注意以后罐子会被混淆。

2 个答案:

答案 0 :(得分:2)

您可以请求发件人的对象:

 public KeyStore getKeyStore(Object obj){
        if (!obj instanceof MyClassThatIsAllowedToCall) return;
        //execute code
 }

当你调用getKeyStore时,总是提供参数:

getKeyStore(this);

这似乎是你想要的,但它并不安全!你很容易伪造发件人。因此,如果您实际处理机密数据,则无法实现这一目标。

答案 1 :(得分:2)

看看StakTraceElement。您可以获得类似的堆栈跟踪:

StackTraceElement[] stack = Thread.currentThread().getStackTrace();

然后您可以使用getMethodName()获取调用方法名称。因此,您可以将要访问的方法列入白名单,并为其返回keystore。对于所有其他情况,您可以返回null。希望这会有所帮助。

相关问题