JavaSecurityManager-如何确保方法仅由另一种方法运行?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (215)

以下是我使用的代码:

public final class A{
    private transient final B sensitiveHolder; //set at Constructor
    public A(B sensitiveHolder){
        this.sensitiveHolder = sensitiveHolder;
    }
    private final byte[] getSensitiveData(){
        return sensitiveHolder.getSensitiveData();
    }
}

public final class B{
    private transient final byte[] sensitiveData;//encrypt and set at Constructor
    public final byte[] getSensitiveData(){
        //check if it is run by A#getSensitiveData(); if it is, decrypt by DEK and give plaintext.
    }
}
提问于
用户回答回答于

你可以这样做:

private boolean verify(final StackTraceElement e[]) {
    boolean doNext = false;
    for (final StackTraceElement s : e) {
        if (doNext && s.getClassName().equals("A") && s.getMethodName().equals("getSensitiveData"))
            return true;
        doNext = s.getMethodName().equals("getStackTrace");
    }
    return false;
}

并调用该方法:

public final byte[] getSensitiveData(StackTraceElement e[]){
    if (verify(e)) {
        // Do something good
    }
}

return sensitiveHolder.getSensitiveData(Thread.currentThread().getStackTrace());
用户回答回答于

这样试试:

package asdf;

import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;

import java.util.EnumSet;
import java.util.List;
import java.util.stream.Collectors;

public class Asdf {

  @Test
  public void what() {
    get();
  }

  void get() {
    StackWalker.StackFrame stackFrame =
        StackWalker.getInstance(EnumSet.of(StackWalker.Option.RETAIN_CLASS_REFERENCE))
            .walk(stream -> {
              List<StackWalker.StackFrame> stackFrames = stream.collect(Collectors.toList());
              return stackFrames.get(1);
            });
    Assertions.assertEquals(Asdf.class, stackFrame.getDeclaringClass());
    Assertions.assertEquals("what", stackFrame.getMethodName());
    Assertions.assertEquals(0, stackFrame.getMethodType().parameterCount());

    // now do caller-sensitive stuff
  }
}

扫码关注云+社区

领取腾讯云代金券

年度创作总结 领取年终奖励