0

I am using the jose4j for implementing token based authentication in my application. I would like to know, if there is any possibility to load JWK from a json stored in the DB. I made folliwing steps:

  1. Created a key: EllipticCurveJsonWebKey key = EcJwkGenerator.generateJwk(EllipticCurves.P521);

  2. Create JSON from it: key.toJson()

  3. Save the json-value to the DB.

  4. Loading value from the DB.

  5. In this point I get stuck. I don't know how to create a key with the data provided in the json.

Any solution?

Community
  • 1
  • 1
N.Zukowski
  • 600
  • 1
  • 12
  • 31

1 Answers1

4

Ok, I found a working solution from this link.

I post the answer which worked for me:

    // Generate a new RSA key pair wrapped in a JWK
    PublicJsonWebKey rsaJwk = RsaJwkGenerator.generateJwk(2048);

    // or an EC key, if you prefer
    PublicJsonWebKey ecJwk = EcJwkGenerator.generateJwk(EllipticCurves.P256);

    // A JSON string with only the public key info
    String publicKeyJwkString = rsaJwk.toJson(JsonWebKey.OutputControlLevel.PUBLIC_ONLY);
    System.out.println(publicKeyJwkString);

    // A JSON string with both the public and private key info
    String keyPairJwkString = rsaJwk.toJson(JsonWebKey.OutputControlLevel.INCLUDE_PRIVATE);
    System.out.println(keyPairJwkString);

    // parse and convert into PublicJsonWebKey/JsonWebKey objects
    PublicJsonWebKey parsedPublicKeyJwk = PublicJsonWebKey.Factory.newPublicJwk(publicKeyJwkString);
    PublicJsonWebKey parsedKeyPairJwk = PublicJsonWebKey.Factory.newPublicJwk(keyPairJwkString);

    // the private key can be used to sign (JWS) or decrypt (JWE)
    PrivateKey privateKey = parsedKeyPairJwk.getPrivateKey();

    // the public key can be used to verify (JWS) or encrypt (JWE)
    PublicKey publicKey = parsedPublicKeyJwk.getPublicKey();
N.Zukowski
  • 600
  • 1
  • 12
  • 31