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:
d
KeyPairGenerator g = KeyPairGenerator.getInstance("EC");
ECGenParameterSpec kpgparams = new ECGenParameterSpec("secp256r1");
g.initialize(kpgparams);
KeyPair pair = g.generateKeyPair();
// Instance of signature class with SHA256withECDSA algorithm
Signature ecdsaSign = Signature.getInstance("SHA256withECDSA");
ecdsaSign.initSign(pair.getPrivate());
System.out.println("Private Keys is::" + pair.getPrivate());
System.out.println("Public Keys is::" + pair.getPublic());
JsonWebKeySet jsonWebKeySet = new JsonWebKeySet();
PrivateKey privateKey = pair.getPrivate();
JsonWebKey webKey = new JsonWebKey(privateKey) {
@Override
public String getKeyType() {
// TODO Auto-generated method stub
return "EC";
}
@Override
protected void fillTypeSpecificParams(Map<String, Object> params,
OutputControlLevel outputLevel) {
params.put("use", "sig");
params.put("key_ops", "sign");
params.put("alg", "ES256");
params.put("kid", "kukuPrivateKey");
}
};
jsonWebKeySet.addJsonWebKey(webKey);
System.out.println("aaaa"+jsonWebKeySet.toJson());
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'