java - 如何让Web App中的类对象始终保持 Activity 状态?

标签 java jakarta-ee encryption

我为我的网络应用程序编写了一个 RSA 类,它生成 key 对来处理加密和解密,其伪代码在这里:

public class RSAFunc {
  private static String CryptMode = "RSA/ECB/PKCS1Padding";
  private static KeyPair kp;
  private static KeyPairGenerator kpg;
  private static RSAPrivateKey privKey;
  private static RSAPublicKey pubkey;

  public RSAFunc() {
    // generate specified length of keypair and store the public and private key
  }


  public String decryptMsg(String msg) {
    // decrypt RSA encrypted message
  }


  public String encryptMsg(String msg) {
    // encrypt message with RSA
  }


  public String getPubKey() {
    // return public key as string
  }
}

但是当我在我的服务器上安装这个 WAR 时,我发现我在每个 session 中总是得到不同的公钥,这意味着我无法解密我的消息,因为 key 是错误的。

有没有办法让对象或变量始终保持 Activity 状态,直到我的 Web 应用程序服务器关闭?

最佳答案

您可以使用Singleton design pattern 。这样,您将能够在整个应用程序中使用相同的对象。

您还可以使用 final 修饰符,这将确保 pubkey 和其他变量仅设置一次。

您的 RSAFunc 类可以如下所示:

public class RSAFunc {

    private static RSAFunc instance = null;

    private final String CryptMode = "RSA/ECB/PKCS1Padding";
    private final KeyPair kp;
    private final KeyPairGenerator kpg;
    private final Key privKey;
    private final RSAPublicKey pubkey;

    private RSAFunc() {
        // generate specified length of keypair and store the public and private key
    }

    public static synchronized RSAFunc getInstance() {
        if (instance == null) {
            instance = new RSAFunc();
        }
        return instance;
    }

    public String decryptMsg(String msg) {
        // decrypt RSA encrypted message
    }

    public String encryptMsg(String msg) {
        // encrypt message with RSA
    }

    public String getPubKey() {
        // return public key as string
    }
}

当您需要 RSAFunc 对象时,请调用 RSAFunc.getInstance(),而不是 new RSAFunc()

关于java - 如何让Web App中的类对象始终保持 Activity 状态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40987473/

相关文章:

java - 获取最新/最新的 HashMap 条目

java - 在 Java 中将 JsonString 解析为 JsonObject

java - 这种取消/中止异步 servlet 处理的方法存在任何问题

jakarta-ee - 来自 Java EE 6 教程的 Duke 案例研究在哪里?

php - MySQL - 如何存储 AES 加密数据?

c# - 加密 web.config 文件中的 <appSettings> 标签

java - 如何在 Eclipse Helios 中设置 JFrame 或 JPanel 背景图片

java - 使用 Spring 设计具有 View 、Web 服务和调度程序的 N 层 Java EE Web 应用程序

python - 我可以使用 AES I.V.或随机数作为密码盐?

java - 我在动态生成二维码时遇到问题