From 9b1ab0f99285f93af55ec6688f0cd021e6b2690d Mon Sep 17 00:00:00 2001 From: Lars Wilhelmsen Date: Mon, 17 Dec 2018 15:58:50 +0100 Subject: [PATCH] KEYCLOAK-9116: Fixes JWK serialization of ECDSA public key coordinates. Signed-off-by: Lars Wilhelmsen --- .../java/org/keycloak/jose/jwk/JWKBuilder.java | 13 ++++++++----- .../test/java/org/keycloak/jose/jwk/JWKTest.java | 15 ++++++++++++--- 2 files changed, 20 insertions(+), 8 deletions(-) diff --git a/core/src/main/java/org/keycloak/jose/jwk/JWKBuilder.java b/core/src/main/java/org/keycloak/jose/jwk/JWKBuilder.java index 8c4a9d8074..9a3677dc1b 100644 --- a/core/src/main/java/org/keycloak/jose/jwk/JWKBuilder.java +++ b/core/src/main/java/org/keycloak/jose/jwk/JWKBuilder.java @@ -77,21 +77,24 @@ public class JWKBuilder { return k; } - public JWK ec(Key key) { ECPublicKey ecKey = (ECPublicKey) key; ECPublicJWK k = new ECPublicJWK(); String kid = this.kid != null ? this.kid : KeyUtils.createKeyId(key); + int fieldSize = ecKey.getParams().getCurve().getField().getFieldSize(); + BigInteger affineX = ecKey.getW().getAffineX(); + BigInteger affineY = ecKey.getW().getAffineY(); + k.setKeyId(kid); k.setKeyType(KeyType.EC); k.setAlgorithm(algorithm); k.setPublicKeyUse(DEFAULT_PUBLIC_KEY_USE); - k.setCrv("P-" + ecKey.getParams().getCurve().getField().getFieldSize()); - k.setX(Base64Url.encode(ecKey.getW().getAffineX().toByteArray())); - k.setY(Base64Url.encode(ecKey.getW().getAffineY().toByteArray())); - + k.setCrv("P-" + fieldSize); + k.setX(Base64Url.encode(toIntegerBytes(ecKey.getW().getAffineX()))); + k.setY(Base64Url.encode(toIntegerBytes(ecKey.getW().getAffineY()))); + return k; } diff --git a/core/src/test/java/org/keycloak/jose/jwk/JWKTest.java b/core/src/test/java/org/keycloak/jose/jwk/JWKTest.java index 9db27fcfc3..0e19bac9b1 100644 --- a/core/src/test/java/org/keycloak/jose/jwk/JWKTest.java +++ b/core/src/test/java/org/keycloak/jose/jwk/JWKTest.java @@ -18,6 +18,7 @@ package org.keycloak.jose.jwk; import org.junit.Test; +import org.keycloak.common.util.Base64Url; import org.keycloak.common.util.KeyUtils; import org.keycloak.crypto.JavaAlgorithm; import org.keycloak.util.JsonSerialization; @@ -86,9 +87,17 @@ public class JWKTest { assertTrue(jwk instanceof ECPublicJWK); - assertNotNull(((ECPublicJWK) jwk).getCrv()); - assertNotNull(((ECPublicJWK) jwk).getX()); - assertNotNull(((ECPublicJWK) jwk).getY()); + ECPublicJWK ecJwk = (ECPublicJWK) jwk; + + assertNotNull(ecJwk.getCrv()); + assertNotNull(ecJwk.getX()); + assertNotNull(ecJwk.getY()); + + byte[] xBytes = Base64Url.decode(ecJwk.getX()); + byte[] yBytes = Base64Url.decode(ecJwk.getY()); + + assertEquals(256/8, xBytes.length); + assertEquals(256/8, yBytes.length); String jwkJson = JsonSerialization.writeValueAsString(jwk);