Search in sources :

Example 11 with KeyWrapper

use of org.keycloak.crypto.KeyWrapper in project keycloak by keycloak.

the class OIDCIdentityProviderPublicKeyLoader method getSavedPublicKey.

protected KeyWrapper getSavedPublicKey() throws Exception {
    KeyWrapper keyWrapper = null;
    if (config.getPublicKeySignatureVerifier() != null && !config.getPublicKeySignatureVerifier().trim().equals("")) {
        PublicKey publicKey = PemUtils.decodePublicKey(config.getPublicKeySignatureVerifier());
        keyWrapper = new KeyWrapper();
        String presetKeyId = config.getPublicKeySignatureVerifierKeyId();
        String kid = (presetKeyId == null || presetKeyId.trim().isEmpty()) ? KeyUtils.createKeyId(publicKey) : presetKeyId;
        keyWrapper.setKid(kid);
        keyWrapper.setType(KeyType.RSA);
        keyWrapper.setAlgorithm(Algorithm.RS256);
        keyWrapper.setUse(KeyUse.SIG);
        keyWrapper.setPublicKey(publicKey);
    } else {
        logger.warnf("No public key saved on identityProvider %s", config.getAlias());
    }
    return keyWrapper;
}
Also used : KeyWrapper(org.keycloak.crypto.KeyWrapper) PublicKey(java.security.PublicKey)

Example 12 with KeyWrapper

use of org.keycloak.crypto.KeyWrapper in project keycloak by keycloak.

the class OAuthClient method verifyToken.

public <T extends JsonWebToken> T verifyToken(String token, Class<T> clazz) {
    try {
        TokenVerifier<T> verifier = TokenVerifier.create(token, clazz);
        String kid = verifier.getHeader().getKeyId();
        String algorithm = verifier.getHeader().getAlgorithm().name();
        KeyWrapper key = getRealmPublicKey(realm, algorithm, kid);
        AsymmetricSignatureVerifierContext verifierContext;
        switch(algorithm) {
            case Algorithm.ES256:
            case Algorithm.ES384:
            case Algorithm.ES512:
                verifierContext = new ServerECDSASignatureVerifierContext(key);
                break;
            default:
                verifierContext = new AsymmetricSignatureVerifierContext(key);
        }
        verifier.verifierContext(verifierContext);
        verifier.verify();
        return verifier.getToken();
    } catch (VerificationException e) {
        throw new RuntimeException("Failed to decode token", e);
    }
}
Also used : KeyWrapper(org.keycloak.crypto.KeyWrapper) AsymmetricSignatureVerifierContext(org.keycloak.crypto.AsymmetricSignatureVerifierContext) VerificationException(org.keycloak.common.VerificationException) ServerECDSASignatureVerifierContext(org.keycloak.crypto.ServerECDSASignatureVerifierContext)

Example 13 with KeyWrapper

use of org.keycloak.crypto.KeyWrapper in project keycloak by keycloak.

the class InfinispanPublicKeyStorageProvider method getPublicKey.

private KeyWrapper getPublicKey(String modelKey, String kid, String algorithm, PublicKeyLoader loader) {
    // Check if key is in cache
    PublicKeysEntry entry = keys.get(modelKey);
    if (entry != null) {
        KeyWrapper publicKey = algorithm != null ? getPublicKeyByAlg(entry.getCurrentKeys(), algorithm) : getPublicKey(entry.getCurrentKeys(), kid);
        if (publicKey != null) {
            return publicKey;
        }
    }
    int lastRequestTime = entry == null ? 0 : entry.getLastRequestTime();
    int currentTime = Time.currentTime();
    // Check if we are allowed to send request
    if (currentTime > lastRequestTime + minTimeBetweenRequests) {
        WrapperCallable wrapperCallable = new WrapperCallable(modelKey, loader);
        FutureTask<PublicKeysEntry> task = new FutureTask<>(wrapperCallable);
        FutureTask<PublicKeysEntry> existing = tasksInProgress.putIfAbsent(modelKey, task);
        if (existing == null) {
            task.run();
        } else {
            task = existing;
        }
        try {
            entry = task.get();
            // Computation finished. Let's see if key is available
            KeyWrapper publicKey = algorithm != null ? getPublicKeyByAlg(entry.getCurrentKeys(), algorithm) : getPublicKey(entry.getCurrentKeys(), kid);
            if (publicKey != null) {
                return publicKey;
            }
        } catch (ExecutionException ee) {
            throw new RuntimeException("Error when loading public keys: " + ee.getMessage(), ee);
        } catch (InterruptedException ie) {
            throw new RuntimeException("Error. Interrupted when loading public keys", ie);
        } finally {
            // Our thread inserted the task. Let's clean
            if (existing == null) {
                tasksInProgress.remove(modelKey);
            }
        }
    } else {
        log.warnf("Won't load the keys for model '%s' . Last request time was %d", modelKey, lastRequestTime);
    }
    Set<String> availableKids = entry == null ? Collections.emptySet() : entry.getCurrentKeys().keySet();
    log.warnf("PublicKey wasn't found in the storage. Requested kid: '%s' . Available kids: '%s'", kid, availableKids);
    return null;
}
Also used : KeyWrapper(org.keycloak.crypto.KeyWrapper) FutureTask(java.util.concurrent.FutureTask) ExecutionException(java.util.concurrent.ExecutionException)

Example 14 with KeyWrapper

use of org.keycloak.crypto.KeyWrapper in project keycloak by keycloak.

the class AbstractOAuth2IdentityProvider method getSignatureContext.

protected SignatureSignerContext getSignatureContext() {
    if (getConfig().getClientAuthMethod().equals(OIDCLoginProtocol.CLIENT_SECRET_JWT)) {
        try (VaultStringSecret vaultStringSecret = session.vault().getStringSecret(getConfig().getClientSecret())) {
            KeyWrapper key = new KeyWrapper();
            String alg = getConfig().getClientAssertionSigningAlg() != null ? getConfig().getClientAssertionSigningAlg() : Algorithm.HS256;
            key.setAlgorithm(alg);
            byte[] decodedSecret = vaultStringSecret.get().orElse(getConfig().getClientSecret()).getBytes();
            SecretKey secret = new SecretKeySpec(decodedSecret, 0, decodedSecret.length, alg);
            key.setSecretKey(secret);
            return new MacSignatureSignerContext(key);
        }
    }
    String alg = getConfig().getClientAssertionSigningAlg() != null ? getConfig().getClientAssertionSigningAlg() : Algorithm.RS256;
    return new AsymmetricSignatureProvider(session, alg).signer();
}
Also used : KeyWrapper(org.keycloak.crypto.KeyWrapper) SecretKey(javax.crypto.SecretKey) VaultStringSecret(org.keycloak.vault.VaultStringSecret) SecretKeySpec(javax.crypto.spec.SecretKeySpec) AsymmetricSignatureProvider(org.keycloak.crypto.AsymmetricSignatureProvider) MacSignatureSignerContext(org.keycloak.crypto.MacSignatureSignerContext)

Example 15 with KeyWrapper

use of org.keycloak.crypto.KeyWrapper in project keycloak by keycloak.

the class HardcodedPublicKeyLoader method getSavedPublicKey.

protected KeyWrapper getSavedPublicKey() {
    KeyWrapper keyWrapper = null;
    if (pem != null && !pem.trim().equals("")) {
        keyWrapper = new KeyWrapper();
        keyWrapper.setKid(kid);
        keyWrapper.setType(KeyType.RSA);
        keyWrapper.setAlgorithm(Algorithm.RS256);
        keyWrapper.setUse(KeyUse.SIG);
        keyWrapper.setPublicKey(PemUtils.decodePublicKey(pem));
    }
    return keyWrapper;
}
Also used : KeyWrapper(org.keycloak.crypto.KeyWrapper)

Aggregations

KeyWrapper (org.keycloak.crypto.KeyWrapper)19 PublicKey (java.security.PublicKey)5 PrivateKey (java.security.PrivateKey)3 SecretKey (javax.crypto.SecretKey)3 SignatureSignerContext (org.keycloak.crypto.SignatureSignerContext)3 JSONWebKeySet (org.keycloak.jose.jwk.JSONWebKeySet)3 UnsupportedEncodingException (java.io.UnsupportedEncodingException)2 Key (java.security.Key)2 Comparator (java.util.Comparator)2 Optional (java.util.Optional)2 Stream (java.util.stream.Stream)2 SecretKeySpec (javax.crypto.spec.SecretKeySpec)2 Logger (org.jboss.logging.Logger)2 Algorithm (org.keycloak.crypto.Algorithm)2 CekManagementProvider (org.keycloak.crypto.CekManagementProvider)2 ContentEncryptionProvider (org.keycloak.crypto.ContentEncryptionProvider)2 KeyUse (org.keycloak.crypto.KeyUse)2 JWEException (org.keycloak.jose.jwe.JWEException)2 JWEAlgorithmProvider (org.keycloak.jose.jwe.alg.JWEAlgorithmProvider)2 JWEEncryptionProvider (org.keycloak.jose.jwe.enc.JWEEncryptionProvider)2