Shu*_*ain 2 java encryption jwt jose4j
我正在生成一个公钥/私钥对,我将使用它通过 jose4j 对 JWT 进行数字签名。它在创建和验证令牌方面也工作得很好。但是一旦我重新启动服务器,之前颁发的令牌就会失效。我觉得每次我重新启动服务器时它都会创建新密钥。这就是我在构造函数中生成密钥的方式:
rsaJsonWebKey = RsaJwkGenerator.generateJwk(2048);
// Give the JWK a Key ID (kid), which is just the polite thing to do
rsaJsonWebKey.setKeyId("secretKey");
Run Code Online (Sandbox Code Playgroud)
当我们尝试创建类的新实例时也会发生这种情况。它说令牌无效。
任何帮助,将不胜感激。谢谢..
每次调用都会RsaJwkGenerator.generateJwk(...)生成一个新的公钥/私钥对。使用私钥签名的 JWT 签名只能使用相应的公钥进行验证(这是安全性的一个重要部分)。底线是,需要为给定的上下文使用适当的密钥,这表明在应用程序中访问密钥的不同方式。
因此,对于需要相同密钥的某个类的不同实例,某种类型的单例密钥可能是合适的。
为了在应用程序重新启动后继续存在,需要以某种方式保存和加载密钥。使用 java 的密钥库是实现此目的的一种方法。或者整个 JWK 的 JSON 可以作为字符串进行访问rsaJsonWebKey.toJson(JsonWebKey.OutputControlLevel.INCLUDE_PRIVATE)并保存在某处。不过,您确实要小心使用私钥,因此请将其保存在安全的地方和/或者您可以使用 JWE 加密整个内容 - 这里显示了其中一些使用基于密码的加密的一些代码:
String jwkjson = rsaJsonWebKey.toJson(JsonWebKey.OutputControlLevel.INCLUDE_PRIVATE);
JsonWebEncryption encryptingJwe = new JsonWebEncryption();
encryptingJwe.setAlgorithmHeaderValue(KeyManagementAlgorithmIdentifiers.PBES2_HS256_A128KW);
encryptingJwe.setEncryptionMethodHeaderParameter(ContentEncryptionAlgorithmIdentifiers.AES_128_CBC_HMAC_SHA_256);
encryptingJwe.setKey(new PbkdfKey("some decent passphrase/password here"));
encryptingJwe.setPayload(jwkjson);
String jweEncryptedJwk = encryptingJwe.getCompactSerialization();
// save jweEncryptedJwk somewhere and load it on application start
JsonWebEncryption decryptingJwe = new JsonWebEncryption();
decryptingJwe.setCompactSerialization(jweEncryptedJwk);
encryptingJwe.setKey(new PbkdfKey("some decent passphrase/password here"));
String payload = encryptingJwe.getPayload();
PublicJsonWebKey publicJsonWebKey = PublicJsonWebKey.Factory.newPublicJwk(payload);
// share the public part with whomever/whatever needs to verify the signatures
System.out.println(publicJsonWebKey.toJson(JsonWebKey.OutputControlLevel.PUBLIC_ONLY));
Run Code Online (Sandbox Code Playgroud)