防止没有 SecurityManager 的反射

问题描述

我正在一个环境中制作一个 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() 并替换它。

有什么办法可以保护键域不被反射?如果没有,我应该怎么做才能保证这些数据的安全?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...