cryptographypublic-key-encryptionjwtecdsajose4j

how to populate a jsonwebkey from a generated ecdsa key


I try to generate a public/private key pair which i will use for digital signature of a JWT with jose4j. I use Elliptic Curve Digital Signature Algorithm

My problem is that i don't know how to get the parameters representing the edcsa key meaning:


Solution

  • You can create a JsonWebKey directly with the public key you generated and jose4j will take care of the parameters and encoding.

        KeyPairGenerator g = KeyPairGenerator.getInstance("EC");
        ECGenParameterSpec kpgparams = new ECGenParameterSpec("secp256r1");
        g.initialize(kpgparams);
    
        KeyPair keyPair = g.generateKeyPair();
    
        PublicJsonWebKey jwk = PublicJsonWebKey.Factory.newPublicJwk(keyPair.getPublic());
        jwk.setPrivateKey(keyPair.getPrivate());
        jwk.setUse(Use.SIGNATURE);
    
        System.out.println(jwk.toJson(JsonWebKey.OutputControlLevel.PUBLIC_ONLY));
        System.out.println(jwk.toJson(JsonWebKey.OutputControlLevel.INCLUDE_PRIVATE)); // to include the private key 'd'
    

    You can also use the EcJwkGenerator utility in jose4j to generate the key pair and wrap it in a JsonWebKey,

        EllipticCurveJsonWebKey jwk = EcJwkGenerator.generateJwk(EllipticCurves.P256);
        jwk.setUse(Use.SIGNATURE);
    
        System.out.println(jwk.toJson(JsonWebKey.OutputControlLevel.PUBLIC_ONLY));
        System.out.println(jwk.toJson(JsonWebKey.OutputControlLevel.INCLUDE_PRIVATE)); // to include the private key 'd'