gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 03:11:27 27 4
gpt4 key购买 nike

我为我的网络应用程序编写了一个 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com