1

I want to save with JOSE4J the JSON representation of a RsaJsonWebKey object in JSON format and then recreate a RsaJsonWebKey object from it again. I have the marshalling part:

RsaJsonWebKey rsaJsonWebKey = RsaJwkGenerator.generateJwk(2048);

String jwkjson = rsaJsonWebKey.toJson(JsonWebKey.OutputControlLevel.INCLUDE_PRIVATE);

but how to unmarshall it and recreate RsaJsonWebKey. That is where I'm stuck as I don't see a constructor of RsaJsonWebKey allowing that.

The question is related to this question

JWT becomes invalid after restarting the server

but it doesn't explain how to unmarshall.

Cœur
  • 37,241
  • 25
  • 195
  • 267
JB007
  • 123
  • 8

1 Answers1

3

The bottom half of the example in JWT becomes invalid after restarting the server does show how to get to a JsonWebKey/PublicJsonWebKey object from a JSON string. Using PublicJsonWebKey publicJsonWebKey = PublicJsonWebKey.Factory.newPublicJwk(jwkJson); will do the parsing/unmarshalling and can be cast to RsaJsonWebKey if need be.

Brian Campbell
  • 2,293
  • 12
  • 13
  • Hi Brian, I wanted to use a none encrypted JSON string. I looked in the sources of JOSE4J and it's possible like this i got the feeling. Haven't tried it yet: Map jwkJsonParsed = JsonUtil.parseJson(jwkJson); RsaJsonWebKey RsaJsonWebKeyRecreated = new RsaJsonWebKey(jwkJsonParsed); ... where jwkJson is the json string i got via String jwkJson = rsaJsonWebKey.toJson(JsonWebKey.OutputControlLevel.INCLUDE_PRIVATE); – JB007 Jun 05 '17 at 18:22
  • PublicJsonWebKey.Factory.newPublicJwk(jwkJson) will parse the JWK JSON into a PublicJsonWebKey object, which will be an instance of RsaJsonWebKey if it's an RSA key. You shouldn't have to do any of that that you mention. But it should work too. – Brian Campbell Jun 05 '17 at 20:17
  • I just used `JsonWebKey.Factory.newJwk(json) as RsaJsonWebKey` to load key for creating new jwt tokens – Homayoun Behzadian Jun 29 '23 at 14:55