Java SecurityManager - 如何确保一个方法只能由另一个方法运行? [英] Java SecurityManager - how to ensure a method is run only by another method?
问题描述
我希望 B 仅由 private
方法 A#getSensitiveData()
运行,该方法使用敏感数据或对敏感数据进行一些处理(例如:加密密钥、国家 ID,随便).
I want B to be run only by the private
method A#getSensitiveData()
that uses or does some processing on sensitive data (example: cryptographic keys, national id, whatever).
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.
}
}
请注意代码会被混淆,因此请不要将任何包名称作为 String
输入.
Please take into account that the code would be obfuscated, so please refrain from putting in any package names as String
.
我必须用SecurityManager#checkPrivilege()
和AccessController.doPrivileged()
写什么才能达到这样的效果?
What must I write with SecurityManager#checkPrivilege()
and AccessController.doPrivileged()
before I can achieve such an effect?
显然这是不同的,因为所谓的答案"不包含任何代码.WORKING CODE 比哦,做这个做那个"更有价值.
Obviously this is different because the so called "answer" does not contain any CODE. WORKING CODE is worth infinitely more than "oh, just do this and that".
推荐答案
你可以这样做:
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
}
}
在你的 A
类中,像这样调用你的 B
类:
In your A
class call your B
class like this:
return sensitiveHolder.getSensitiveData(Thread.currentThread().getStackTrace());
我不知道这是您需要的还是接近的.您可以使用 if
的 equals
部分中的值.我从 this 站点获取并修改了示例.
I don't know if this is what you need or it is near that. You could play around the values in the equals
section of the if
. I got and modified the example from this site.
这篇关于Java SecurityManager - 如何确保一个方法只能由另一个方法运行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!