我正在一个环境中制作一个java程序,该程序从“加载目录”中的文件加载代码。这个环境在它已经设置了一个不可替换的SecurityManager
. 我试图隐藏SecretKey
任何恶意代码,这些代码也可以以与我相同的方式加载。在没有安全管理器的情况下隐藏一个字段以防止反射似乎非常困难,如果不是不可能的话。该代码的目的是保护最终用户免受放在“加载目录”中的任何恶意代码的侵害。
这是我的代码:
public class KeyStore {
private static SecretKey key = null;
public static SecretKey getKey() {
if (!Utils.getCallerClassName(1).startsWith("my.package.and.ClassName")) throw new SecurityException("Not allowed to get security key!");
return key;
}
public static void setKey(SecretKey key) {
if (!Utils.getCallerClassName(1).startsWith("my.package.and.ClassName")) throw new SecurityException("Not allowed to set security key!");
if (KeyStore.key == null)
KeyStore.key = key;
}
}
其中 Utils.getCallerClassName() 是:
public static String getCallerClassName(int howFarBack) {
StackTraceElement[] stElements = Thread.currentThread().getStackTrace();
if (stElements.length >= howFarBack + 3) return stElements[howFarBack + 2 /* One for getCallerClassName() and one for getStackTrace() */].getClassName();
return stElements[stElements.length-1].getClassName();
}
加载的SecurityManager
只是阻止 System.exit() 并替换它。
有什么方法可以保护关键字段不被反射?如果没有,我应该怎么做才能保证这些数据的安全?