Search in sources :

Example 1 with JWEAlgorithmProvider

use of org.keycloak.jose.jwe.alg.JWEAlgorithmProvider in project keycloak by keycloak.

the class JWETest method testKeyEncryption_ContentEncryptionAesGcm.

private void testKeyEncryption_ContentEncryptionAesGcm(String jweAlgorithmName, String jweEncryptionName) throws Exception {
    // generate key pair for KEK
    KeyPair keyPair = KeyUtils.generateRsaKeyPair(2048);
    JWEAlgorithmProvider jweAlgorithmProvider = new RsaKeyEncryptionJWEAlgorithmProvider(getJcaAlgorithmName(jweAlgorithmName));
    JWEEncryptionProvider jweEncryptionProvider = new AesGcmJWEEncryptionProvider(jweEncryptionName);
    JWEHeader jweHeader = new JWEHeader(jweAlgorithmName, jweEncryptionName, null);
    JWE jwe = new JWE().header(jweHeader).content(PAYLOAD.getBytes(StandardCharsets.UTF_8));
    jwe.getKeyStorage().setEncryptionKey(keyPair.getPublic());
    String encodedContent = jwe.encodeJwe(jweAlgorithmProvider, jweEncryptionProvider);
    System.out.println("Encoded content: " + encodedContent);
    System.out.println("Encoded content length: " + encodedContent.length());
    jwe = new JWE();
    jwe.getKeyStorage().setDecryptionKey(keyPair.getPrivate());
    jwe.verifyAndDecodeJwe(encodedContent, jweAlgorithmProvider, jweEncryptionProvider);
    String decodedContent = new String(jwe.getContent(), StandardCharsets.UTF_8);
    System.out.println("Decoded content: " + decodedContent);
    System.out.println("Decoded content length: " + decodedContent.length());
    Assert.assertEquals(PAYLOAD, decodedContent);
}
Also used : KeyPair(java.security.KeyPair) RsaKeyEncryptionJWEAlgorithmProvider(org.keycloak.jose.jwe.alg.RsaKeyEncryptionJWEAlgorithmProvider) JWEAlgorithmProvider(org.keycloak.jose.jwe.alg.JWEAlgorithmProvider) RsaKeyEncryptionJWEAlgorithmProvider(org.keycloak.jose.jwe.alg.RsaKeyEncryptionJWEAlgorithmProvider) AesGcmJWEEncryptionProvider(org.keycloak.jose.jwe.enc.AesGcmJWEEncryptionProvider) JWEEncryptionProvider(org.keycloak.jose.jwe.enc.JWEEncryptionProvider) AesCbcHmacShaJWEEncryptionProvider(org.keycloak.jose.jwe.enc.AesCbcHmacShaJWEEncryptionProvider) AesGcmJWEEncryptionProvider(org.keycloak.jose.jwe.enc.AesGcmJWEEncryptionProvider)

Example 2 with JWEAlgorithmProvider

use of org.keycloak.jose.jwe.alg.JWEAlgorithmProvider in project keycloak by keycloak.

the class DefaultTokenManager method getEncryptedToken.

private String getEncryptedToken(TokenCategory category, String encodedToken) {
    String encryptedToken = null;
    String algAlgorithm = cekManagementAlgorithm(category);
    String encAlgorithm = encryptAlgorithm(category);
    CekManagementProvider cekManagementProvider = session.getProvider(CekManagementProvider.class, algAlgorithm);
    JWEAlgorithmProvider jweAlgorithmProvider = cekManagementProvider.jweAlgorithmProvider();
    ContentEncryptionProvider contentEncryptionProvider = session.getProvider(ContentEncryptionProvider.class, encAlgorithm);
    JWEEncryptionProvider jweEncryptionProvider = contentEncryptionProvider.jweEncryptionProvider();
    ClientModel client = session.getContext().getClient();
    KeyWrapper keyWrapper = PublicKeyStorageManager.getClientPublicKeyWrapper(session, client, JWK.Use.ENCRYPTION, algAlgorithm);
    if (keyWrapper == null) {
        throw new RuntimeException("can not get encryption KEK");
    }
    Key encryptionKek = keyWrapper.getPublicKey();
    String encryptionKekId = keyWrapper.getKid();
    try {
        encryptedToken = TokenUtil.jweKeyEncryptionEncode(encryptionKek, encodedToken.getBytes("UTF-8"), algAlgorithm, encAlgorithm, encryptionKekId, jweAlgorithmProvider, jweEncryptionProvider);
    } catch (JWEException | UnsupportedEncodingException e) {
        throw new RuntimeException(e);
    }
    return encryptedToken;
}
Also used : KeyWrapper(org.keycloak.crypto.KeyWrapper) ClientModel(org.keycloak.models.ClientModel) ContentEncryptionProvider(org.keycloak.crypto.ContentEncryptionProvider) JWEAlgorithmProvider(org.keycloak.jose.jwe.alg.JWEAlgorithmProvider) JWEException(org.keycloak.jose.jwe.JWEException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) JWEEncryptionProvider(org.keycloak.jose.jwe.enc.JWEEncryptionProvider) Key(java.security.Key) PrivateKey(java.security.PrivateKey) CekManagementProvider(org.keycloak.crypto.CekManagementProvider)

Example 3 with JWEAlgorithmProvider

use of org.keycloak.jose.jwe.alg.JWEAlgorithmProvider in project keycloak by keycloak.

the class AuthorizationTokenEncryptionTest method testAuthorizationTokenSignatureAndEncryption.

private void testAuthorizationTokenSignatureAndEncryption(String sigAlgorithm, String algAlgorithm, String encAlgorithm) {
    ClientResource clientResource;
    ClientRepresentation clientRep;
    try {
        // generate and register encryption key onto client
        TestOIDCEndpointsApplicationResource oidcClientEndpointsResource = testingClient.testApp().oidcClientEndpoints();
        oidcClientEndpointsResource.generateKeys(algAlgorithm);
        clientResource = ApiUtil.findClientByClientId(adminClient.realm("test"), "test-app");
        clientRep = clientResource.toRepresentation();
        // set authorization response signature algorithm and encryption algorithms
        OIDCAdvancedConfigWrapper.fromClientRepresentation(clientRep).setAuthorizationSignedResponseAlg(sigAlgorithm);
        OIDCAdvancedConfigWrapper.fromClientRepresentation(clientRep).setAuthorizationEncryptedResponseAlg(algAlgorithm);
        OIDCAdvancedConfigWrapper.fromClientRepresentation(clientRep).setAuthorizationEncryptedResponseEnc(encAlgorithm);
        // use and set jwks_url
        OIDCAdvancedConfigWrapper.fromClientRepresentation(clientRep).setUseJwksUrl(true);
        String jwksUrl = TestApplicationResourceUrls.clientJwksUri();
        OIDCAdvancedConfigWrapper.fromClientRepresentation(clientRep).setJwksUrl(jwksUrl);
        clientResource.update(clientRep);
        // get authorization response
        oauth.responseMode("jwt");
        oauth.stateParamHardcoded("OpenIdConnect.AuthenticationProperties=2302984sdlk");
        OAuthClient.AuthorizationEndpointResponse response = oauth.doLogin("test-user@localhost", "password");
        // parse JWE and JOSE Header
        String jweStr = response.getResponse();
        String[] parts = jweStr.split("\\.");
        Assert.assertEquals(parts.length, 5);
        // get decryption key
        // not publickey , use privateKey
        Map<String, String> keyPair = oidcClientEndpointsResource.getKeysAsPem();
        PrivateKey decryptionKEK = PemUtils.decodePrivateKey(keyPair.get("privateKey"));
        // verify and decrypt JWE
        JWEAlgorithmProvider algorithmProvider = getJweAlgorithmProvider(algAlgorithm);
        JWEEncryptionProvider encryptionProvider = getJweEncryptionProvider(encAlgorithm);
        byte[] decodedString = TokenUtil.jweKeyEncryptionVerifyAndDecode(decryptionKEK, jweStr, algorithmProvider, encryptionProvider);
        String authorizationTokenString = new String(decodedString, "UTF-8");
        // a nested JWT (signed and encrypted JWT) needs to set "JWT" to its JOSE Header's "cty" field
        JWEHeader jweHeader = (JWEHeader) getHeader(parts[0]);
        Assert.assertEquals("JWT", jweHeader.getContentType());
        // verify JWS
        AuthorizationResponseToken authorizationToken = oauth.verifyAuthorizationResponseToken(authorizationTokenString);
        Assert.assertEquals("test-app", authorizationToken.getAudience()[0]);
        Assert.assertEquals("OpenIdConnect.AuthenticationProperties=2302984sdlk", authorizationToken.getOtherClaims().get("state"));
        Assert.assertNotNull(authorizationToken.getOtherClaims().get("code"));
    } catch (JWEException | UnsupportedEncodingException e) {
        Assert.fail();
    } finally {
        clientResource = ApiUtil.findClientByClientId(adminClient.realm("test"), "test-app");
        clientRep = clientResource.toRepresentation();
        // revert id token signature algorithm and encryption algorithms
        OIDCAdvancedConfigWrapper.fromClientRepresentation(clientRep).setAuthorizationSignedResponseAlg(Algorithm.RS256);
        OIDCAdvancedConfigWrapper.fromClientRepresentation(clientRep).setAuthorizationEncryptedResponseAlg(null);
        OIDCAdvancedConfigWrapper.fromClientRepresentation(clientRep).setAuthorizationEncryptedResponseEnc(null);
        // revert jwks_url settings
        OIDCAdvancedConfigWrapper.fromClientRepresentation(clientRep).setUseJwksUrl(false);
        OIDCAdvancedConfigWrapper.fromClientRepresentation(clientRep).setJwksUrl(null);
        clientResource.update(clientRep);
    }
}
Also used : AuthorizationResponseToken(org.keycloak.representations.AuthorizationResponseToken) PrivateKey(java.security.PrivateKey) TestOIDCEndpointsApplicationResource(org.keycloak.testsuite.client.resources.TestOIDCEndpointsApplicationResource) JWEAlgorithmProvider(org.keycloak.jose.jwe.alg.JWEAlgorithmProvider) OAuthClient(org.keycloak.testsuite.util.OAuthClient) JWEException(org.keycloak.jose.jwe.JWEException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) JWEEncryptionProvider(org.keycloak.jose.jwe.enc.JWEEncryptionProvider) ClientRepresentation(org.keycloak.representations.idm.ClientRepresentation) JWEHeader(org.keycloak.jose.jwe.JWEHeader) ClientResource(org.keycloak.admin.client.resource.ClientResource)

Example 4 with JWEAlgorithmProvider

use of org.keycloak.jose.jwe.alg.JWEAlgorithmProvider in project keycloak by keycloak.

the class IdTokenEncryptionTest method testIdTokenSignatureAndEncryption.

private void testIdTokenSignatureAndEncryption(String sigAlgorithm, String algAlgorithm, String encAlgorithm) {
    ClientResource clientResource = null;
    ClientRepresentation clientRep = null;
    try {
        // generate and register encryption key onto client
        TestOIDCEndpointsApplicationResource oidcClientEndpointsResource = testingClient.testApp().oidcClientEndpoints();
        oidcClientEndpointsResource.generateKeys(algAlgorithm);
        clientResource = ApiUtil.findClientByClientId(adminClient.realm("test"), "test-app");
        clientRep = clientResource.toRepresentation();
        // set id token signature algorithm and encryption algorithms
        OIDCAdvancedConfigWrapper.fromClientRepresentation(clientRep).setIdTokenSignedResponseAlg(sigAlgorithm);
        OIDCAdvancedConfigWrapper.fromClientRepresentation(clientRep).setIdTokenEncryptedResponseAlg(algAlgorithm);
        OIDCAdvancedConfigWrapper.fromClientRepresentation(clientRep).setIdTokenEncryptedResponseEnc(encAlgorithm);
        // use and set jwks_url
        OIDCAdvancedConfigWrapper.fromClientRepresentation(clientRep).setUseJwksUrl(true);
        String jwksUrl = TestApplicationResourceUrls.clientJwksUri();
        OIDCAdvancedConfigWrapper.fromClientRepresentation(clientRep).setJwksUrl(jwksUrl);
        clientResource.update(clientRep);
        // get id token
        OAuthClient.AuthorizationEndpointResponse response = oauth.doLogin("test-user@localhost", "password");
        String code = response.getCode();
        OAuthClient.AccessTokenResponse tokenResponse = oauth.doAccessTokenRequest(code, "password");
        // parse JWE and JOSE Header
        String jweStr = tokenResponse.getIdToken();
        String[] parts = jweStr.split("\\.");
        Assert.assertEquals(parts.length, 5);
        // get decryption key
        // not publickey , use privateKey
        Map<String, String> keyPair = oidcClientEndpointsResource.getKeysAsPem();
        PrivateKey decryptionKEK = PemUtils.decodePrivateKey(keyPair.get("privateKey"));
        // a nested JWT (signed and encrypted JWT) needs to set "JWT" to its JOSE Header's "cty" field
        JWEHeader jweHeader = (JWEHeader) getHeader(parts[0]);
        Assert.assertEquals("JWT", jweHeader.getContentType());
        // verify and decrypt JWE
        JWEAlgorithmProvider algorithmProvider = getJweAlgorithmProvider(algAlgorithm);
        JWEEncryptionProvider encryptionProvider = getJweEncryptionProvider(encAlgorithm);
        byte[] decodedString = TokenUtil.jweKeyEncryptionVerifyAndDecode(decryptionKEK, jweStr, algorithmProvider, encryptionProvider);
        String idTokenString = new String(decodedString, "UTF-8");
        // verify JWS
        IDToken idToken = oauth.verifyIDToken(idTokenString);
        Assert.assertEquals("test-user@localhost", idToken.getPreferredUsername());
        Assert.assertEquals("test-app", idToken.getIssuedFor());
    } catch (JWEException | UnsupportedEncodingException e) {
        Assert.fail();
    } finally {
        clientResource = ApiUtil.findClientByClientId(adminClient.realm("test"), "test-app");
        clientRep = clientResource.toRepresentation();
        // revert id token signature algorithm and encryption algorithms
        OIDCAdvancedConfigWrapper.fromClientRepresentation(clientRep).setIdTokenSignedResponseAlg(Algorithm.RS256);
        OIDCAdvancedConfigWrapper.fromClientRepresentation(clientRep).setIdTokenEncryptedResponseAlg(null);
        OIDCAdvancedConfigWrapper.fromClientRepresentation(clientRep).setIdTokenEncryptedResponseEnc(null);
        // revert jwks_url settings
        OIDCAdvancedConfigWrapper.fromClientRepresentation(clientRep).setUseJwksUrl(false);
        OIDCAdvancedConfigWrapper.fromClientRepresentation(clientRep).setJwksUrl(null);
        clientResource.update(clientRep);
    }
}
Also used : PrivateKey(java.security.PrivateKey) TestOIDCEndpointsApplicationResource(org.keycloak.testsuite.client.resources.TestOIDCEndpointsApplicationResource) JWEAlgorithmProvider(org.keycloak.jose.jwe.alg.JWEAlgorithmProvider) OAuthClient(org.keycloak.testsuite.util.OAuthClient) JWEException(org.keycloak.jose.jwe.JWEException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) JWEEncryptionProvider(org.keycloak.jose.jwe.enc.JWEEncryptionProvider) ClientRepresentation(org.keycloak.representations.idm.ClientRepresentation) JWEHeader(org.keycloak.jose.jwe.JWEHeader) AccessTokenResponse(org.keycloak.testsuite.util.OAuthClient.AccessTokenResponse) ClientResource(org.keycloak.admin.client.resource.ClientResource) IDToken(org.keycloak.representations.IDToken)

Example 5 with JWEAlgorithmProvider

use of org.keycloak.jose.jwe.alg.JWEAlgorithmProvider in project keycloak by keycloak.

the class JWETest method testKeyEncryption_ContentEncryptionAesHmacSha.

private void testKeyEncryption_ContentEncryptionAesHmacSha(String jweAlgorithmName, String jweEncryptionName) throws Exception {
    // generate key pair for KEK
    KeyPair keyPair = KeyUtils.generateRsaKeyPair(2048);
    // generate CEK
    final SecretKey aesKey = new SecretKeySpec(AES_128_KEY, "AES");
    final SecretKey hmacKey = new SecretKeySpec(HMAC_SHA256_KEY, "HMACSHA2");
    JWEAlgorithmProvider jweAlgorithmProvider = new RsaKeyEncryptionJWEAlgorithmProvider(getJcaAlgorithmName(jweAlgorithmName));
    JWEEncryptionProvider jweEncryptionProvider = new AesCbcHmacShaJWEEncryptionProvider(jweEncryptionName);
    JWEHeader jweHeader = new JWEHeader(jweAlgorithmName, jweEncryptionName, null);
    JWE jwe = new JWE().header(jweHeader).content(PAYLOAD.getBytes(StandardCharsets.UTF_8));
    jwe.getKeyStorage().setEncryptionKey(keyPair.getPublic());
    jwe.getKeyStorage().setCEKKey(aesKey, JWEKeyStorage.KeyUse.ENCRYPTION).setCEKKey(hmacKey, JWEKeyStorage.KeyUse.SIGNATURE);
    String encodedContent = jwe.encodeJwe(jweAlgorithmProvider, jweEncryptionProvider);
    System.out.println("Encoded content: " + encodedContent);
    System.out.println("Encoded content length: " + encodedContent.length());
    jwe = new JWE();
    jwe.getKeyStorage().setDecryptionKey(keyPair.getPrivate());
    jwe.getKeyStorage().setCEKKey(aesKey, JWEKeyStorage.KeyUse.ENCRYPTION).setCEKKey(hmacKey, JWEKeyStorage.KeyUse.SIGNATURE);
    jwe.verifyAndDecodeJwe(encodedContent, jweAlgorithmProvider, jweEncryptionProvider);
    String decodedContent = new String(jwe.getContent(), StandardCharsets.UTF_8);
    System.out.println("Decoded content: " + decodedContent);
    System.out.println("Decoded content length: " + decodedContent.length());
    Assert.assertEquals(PAYLOAD, decodedContent);
}
Also used : KeyPair(java.security.KeyPair) SecretKey(javax.crypto.SecretKey) RsaKeyEncryptionJWEAlgorithmProvider(org.keycloak.jose.jwe.alg.RsaKeyEncryptionJWEAlgorithmProvider) JWEAlgorithmProvider(org.keycloak.jose.jwe.alg.JWEAlgorithmProvider) SecretKeySpec(javax.crypto.spec.SecretKeySpec) RsaKeyEncryptionJWEAlgorithmProvider(org.keycloak.jose.jwe.alg.RsaKeyEncryptionJWEAlgorithmProvider) AesCbcHmacShaJWEEncryptionProvider(org.keycloak.jose.jwe.enc.AesCbcHmacShaJWEEncryptionProvider) AesGcmJWEEncryptionProvider(org.keycloak.jose.jwe.enc.AesGcmJWEEncryptionProvider) JWEEncryptionProvider(org.keycloak.jose.jwe.enc.JWEEncryptionProvider) AesCbcHmacShaJWEEncryptionProvider(org.keycloak.jose.jwe.enc.AesCbcHmacShaJWEEncryptionProvider)

Aggregations

JWEAlgorithmProvider (org.keycloak.jose.jwe.alg.JWEAlgorithmProvider)5 JWEEncryptionProvider (org.keycloak.jose.jwe.enc.JWEEncryptionProvider)5 UnsupportedEncodingException (java.io.UnsupportedEncodingException)3 PrivateKey (java.security.PrivateKey)3 JWEException (org.keycloak.jose.jwe.JWEException)3 KeyPair (java.security.KeyPair)2 ClientResource (org.keycloak.admin.client.resource.ClientResource)2 JWEHeader (org.keycloak.jose.jwe.JWEHeader)2 RsaKeyEncryptionJWEAlgorithmProvider (org.keycloak.jose.jwe.alg.RsaKeyEncryptionJWEAlgorithmProvider)2 AesCbcHmacShaJWEEncryptionProvider (org.keycloak.jose.jwe.enc.AesCbcHmacShaJWEEncryptionProvider)2 AesGcmJWEEncryptionProvider (org.keycloak.jose.jwe.enc.AesGcmJWEEncryptionProvider)2 ClientRepresentation (org.keycloak.representations.idm.ClientRepresentation)2 TestOIDCEndpointsApplicationResource (org.keycloak.testsuite.client.resources.TestOIDCEndpointsApplicationResource)2 OAuthClient (org.keycloak.testsuite.util.OAuthClient)2 Key (java.security.Key)1 SecretKey (javax.crypto.SecretKey)1 SecretKeySpec (javax.crypto.spec.SecretKeySpec)1 CekManagementProvider (org.keycloak.crypto.CekManagementProvider)1 ContentEncryptionProvider (org.keycloak.crypto.ContentEncryptionProvider)1 KeyWrapper (org.keycloak.crypto.KeyWrapper)1