Search in sources :

Example 1 with Algorithm

use of io.jans.as.model.jwk.Algorithm in project jans by JanssenProject.

the class AbstractCryptoProvider method processKey.

private PublicKey processKey(Algorithm requestedAlgorithm, String alias, JSONObject key) throws NoSuchAlgorithmException, InvalidKeySpecException, InvalidParameterSpecException, InvalidParameterException {
    PublicKey publicKey = null;
    AlgorithmFamily algorithmFamily = null;
    if (key.has(JWKParameter.ALGORITHM)) {
        Algorithm algorithm = Algorithm.fromString(key.optString(JWKParameter.ALGORITHM));
        if (requestedAlgorithm != null && !requestedAlgorithm.equals(algorithm)) {
            LOG.trace("kid matched but algorithm does not match. kid algorithm:" + algorithm + ", requestedAlgorithm:" + requestedAlgorithm + ", kid:" + alias);
            return null;
        }
        algorithmFamily = algorithm.getFamily();
    } else if (key.has(JWKParameter.KEY_TYPE)) {
        algorithmFamily = AlgorithmFamily.fromString(key.getString(JWKParameter.KEY_TYPE));
    } else {
        throw new InvalidParameterException("Wrong key (JSONObject): doesn't contain 'alg' and 'kty' properties");
    }
    switch(algorithmFamily) {
        case RSA:
            {
                KeyFactory keyFactory = KeyFactory.getInstance("RSA");
                RSAPublicKeySpec pubKeySpec = new RSAPublicKeySpec(new BigInteger(1, Base64Util.base64urldecode(key.getString(JWKParameter.MODULUS))), new BigInteger(1, Base64Util.base64urldecode(key.getString(JWKParameter.EXPONENT))));
                publicKey = keyFactory.generatePublic(pubKeySpec);
                break;
            }
        case EC:
            {
                EllipticEdvardsCurve curve = EllipticEdvardsCurve.fromString(key.optString(JWKParameter.CURVE));
                AlgorithmParameters parameters = AlgorithmParameters.getInstance(AlgorithmFamily.EC.toString());
                parameters.init(new ECGenParameterSpec(curve.getAlias()));
                ECParameterSpec ecParameters = parameters.getParameterSpec(ECParameterSpec.class);
                publicKey = KeyFactory.getInstance(AlgorithmFamily.EC.toString()).generatePublic(new ECPublicKeySpec(new ECPoint(new BigInteger(1, Base64Util.base64urldecode(key.getString(JWKParameter.X))), new BigInteger(1, Base64Util.base64urldecode(key.getString(JWKParameter.Y)))), ecParameters));
                break;
            }
        case ED:
            {
                X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(Base64Util.base64urldecode(key.getString(JWKParameter.X)));
                publicKey = KeyFactory.getInstance(key.optString(JWKParameter.ALGORITHM)).generatePublic(publicKeySpec);
                break;
            }
        default:
            {
                throw new InvalidParameterException(String.format("Wrong AlgorithmFamily value: %s", algorithmFamily));
            }
    }
    if (key.has(JWKParameter.EXPIRATION_TIME)) {
        checkKeyExpiration(alias, key.getLong(JWKParameter.EXPIRATION_TIME));
    }
    return publicKey;
}
Also used : PublicKey(java.security.PublicKey) ECGenParameterSpec(java.security.spec.ECGenParameterSpec) X509EncodedKeySpec(java.security.spec.X509EncodedKeySpec) RSAPublicKeySpec(java.security.spec.RSAPublicKeySpec) EllipticEdvardsCurve(io.jans.as.model.crypto.signature.EllipticEdvardsCurve) ECPoint(java.security.spec.ECPoint) SignatureAlgorithm(io.jans.as.model.crypto.signature.SignatureAlgorithm) Algorithm(io.jans.as.model.jwk.Algorithm) AlgorithmFamily(io.jans.as.model.crypto.signature.AlgorithmFamily) ECPublicKeySpec(java.security.spec.ECPublicKeySpec) InvalidParameterException(io.jans.as.model.exception.InvalidParameterException) ECParameterSpec(java.security.spec.ECParameterSpec) BigInteger(java.math.BigInteger) KeyFactory(java.security.KeyFactory) AlgorithmParameters(java.security.AlgorithmParameters)

Example 2 with Algorithm

use of io.jans.as.model.jwk.Algorithm in project jans by JanssenProject.

the class AbstractCryptoProvider method generateJwks.

public static JSONObject generateJwks(AbstractCryptoProvider cryptoProvider, AppConfiguration configuration) {
    GregorianCalendar expirationTime = new GregorianCalendar(TimeZone.getTimeZone("UTC"));
    expirationTime.add(Calendar.HOUR, configuration.getKeyRegenerationInterval());
    expirationTime.add(Calendar.SECOND, configuration.getIdTokenLifetime());
    long expiration = expirationTime.getTimeInMillis();
    final List<String> allowedAlgs = configuration.getKeyAlgsAllowedForGeneration();
    JSONArray keys = new JSONArray();
    for (Algorithm alg : Algorithm.values()) {
        try {
            final boolean isNotAllowed = !allowedAlgs.isEmpty() && !allowedAlgs.contains(alg.getParamName());
            final boolean isNotSupported = !alg.canGenerateKeys();
            if (isNotAllowed || isNotSupported) {
                if (isNotAllowed) {
                    LOG.debug(String.format("Key generation for %s is skipped because it's not allowed by keyAlgsAllowedForGeneration configuration property.", alg.toString()));
                }
                if (isNotSupported) {
                    LOG.trace(alg + " does not support keys re-generation.");
                }
                continue;
            }
            keys.put(cryptoProvider.generateKey(alg, expiration));
        } catch (Exception ex) {
            LOG.error(String.format("Algorithm: %s", alg), ex);
        }
    }
    JSONObject jsonObject = new JSONObject();
    jsonObject.put(JWKParameter.JSON_WEB_KEY_SET, keys);
    return jsonObject;
}
Also used : JSONObject(org.json.JSONObject) GregorianCalendar(java.util.GregorianCalendar) JSONArray(org.json.JSONArray) SignatureAlgorithm(io.jans.as.model.crypto.signature.SignatureAlgorithm) Algorithm(io.jans.as.model.jwk.Algorithm) CryptoProviderException(io.jans.as.model.exception.CryptoProviderException) InvalidKeySpecException(java.security.spec.InvalidKeySpecException) InvalidParameterSpecException(java.security.spec.InvalidParameterSpecException) InvalidParameterException(io.jans.as.model.exception.InvalidParameterException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException)

Example 3 with Algorithm

use of io.jans.as.model.jwk.Algorithm in project jans by JanssenProject.

the class GetTokensByCodeOperation method execute.

@Override
public IOpResponse execute(GetTokensByCodeParams params) throws Exception {
    validate(params);
    final Rp rp = getRp();
    OpenIdConfigurationResponse discoveryResponse = getDiscoveryService().getConnectDiscoveryResponse(rp);
    final TokenRequest tokenRequest = new TokenRequest(GrantType.AUTHORIZATION_CODE);
    tokenRequest.setCode(params.getCode());
    tokenRequest.setRedirectUri(rp.getRedirectUri());
    tokenRequest.setAuthUsername(rp.getClientId());
    AuthenticationMethod authenticationMethod = Strings.isNullOrEmpty(params.getAuthenticationMethod()) ? AuthenticationMethod.fromString(rp.getTokenEndpointAuthMethod()) : AuthenticationMethod.fromString(params.getAuthenticationMethod());
    if (authenticationMethod == null) {
        LOG.debug("TokenEndpointAuthMethod is either not set or not valid. Setting `client_secret_basic` as AuthenticationMethod. TokenEndpointAuthMethod : {} ", rp.getTokenEndpointAuthMethod());
        tokenRequest.setAuthenticationMethod(AuthenticationMethod.CLIENT_SECRET_BASIC);
    } else {
        tokenRequest.setAuthenticationMethod(authenticationMethod);
    }
    if (Lists.newArrayList(AuthenticationMethod.PRIVATE_KEY_JWT, AuthenticationMethod.TLS_CLIENT_AUTH, AuthenticationMethod.SELF_SIGNED_TLS_CLIENT_AUTH).contains(authenticationMethod)) {
        Algorithm algorithm = Strings.isNullOrEmpty(params.getAlgorithm()) ? Algorithm.fromString(rp.getTokenEndpointAuthSigningAlg()) : Algorithm.fromString(params.getAlgorithm());
        if (algorithm == null) {
            LOG.error("TokenEndpointAuthSigningAlg is either not set or not valid. TokenEndpointAuthSigningAlg : {} ", rp.getTokenEndpointAuthSigningAlg());
            throw new HttpException(ErrorResponseCode.INVALID_SIGNATURE_ALGORITHM);
        }
        tokenRequest.setAlgorithm(SignatureAlgorithm.fromString(rp.getTokenEndpointAuthSigningAlg()));
        if (!getConfigurationService().getConfiguration().getEnableJwksGeneration()) {
            LOG.error("The Token Authentication Method is {}. Please set `enable_jwks_generation` (to `true`), `crypt_provider_key_store_path` and `crypt_provider_key_store_password` in `client-api-server.yml` to enable RP-jwks generation in jans-client-api.", authenticationMethod.toString());
            throw new HttpException(ErrorResponseCode.JWKS_GENERATION_DISABLE);
        }
        tokenRequest.setCryptoProvider(getKeyGeneratorService().getCryptoProvider());
        tokenRequest.setKeyId(getKeyGeneratorService().getCryptoProvider().getKeyId(getKeyGeneratorService().getKeys(), algorithm, Use.SIGNATURE));
        tokenRequest.setAudience(discoveryResponse.getTokenEndpoint());
    } else {
        tokenRequest.setAuthPassword(rp.getClientSecret());
    }
    final TokenClient tokenClient = getOpClientFactory().createTokenClient(discoveryResponse.getTokenEndpoint());
    tokenClient.setExecutor(getHttpService().getClientEngine());
    tokenClient.setRequest(tokenRequest);
    final TokenResponse response = tokenClient.exec();
    if (response.getStatus() == 200 || response.getStatus() == 302) {
        if (Strings.isNullOrEmpty(response.getIdToken())) {
            LOG.error("id_token is not returned. Please check: 1) OP log file for error (oxauth.log) 2) whether 'openid' scope is present for 'get_authorization_url' command");
            LOG.error("Entity: " + response.getEntity());
            throw new HttpException(ErrorResponseCode.NO_ID_TOKEN_RETURNED);
        }
        if (Strings.isNullOrEmpty(response.getAccessToken())) {
            LOG.error("access_token is not returned");
            throw new HttpException(ErrorResponseCode.NO_ACCESS_TOKEN_RETURNED);
        }
        final Jwt idToken = Jwt.parse(response.getIdToken());
        final Validator validator = new Validator.Builder().discoveryResponse(discoveryResponse).idToken(idToken).keyService(getKeyService()).opClientFactory(getOpClientFactory()).rpServerConfiguration(getConfigurationService().getConfiguration()).rp(rp).build();
        String state = getStateService().encodeExpiredObject(params.getState(), ExpiredObjectType.STATE);
        validator.validateNonce(getStateService());
        validator.validateIdToken();
        validator.validateAccessToken(response.getAccessToken());
        validator.validateState(state);
        // persist tokens
        rp.setIdToken(response.getIdToken());
        rp.setAccessToken(response.getAccessToken());
        getRpService().update(rp);
        getStateService().deleteExpiredObjectsByKey(state);
        LOG.trace("Scope: " + response.getScope());
        final GetTokensByCodeResponse opResponse = new GetTokensByCodeResponse();
        opResponse.setAccessToken(response.getAccessToken());
        opResponse.setIdToken(response.getIdToken());
        opResponse.setRefreshToken(response.getRefreshToken());
        opResponse.setExpiresIn(response.getExpiresIn() != null ? response.getExpiresIn() : -1);
        opResponse.setIdTokenClaims(Jackson2.createJsonMapper().readTree(idToken.getClaims().toJsonString()));
        return opResponse;
    } else {
        if (response.getStatus() == 400) {
            throw new HttpException(ErrorResponseCode.BAD_REQUEST_INVALID_CODE);
        }
        LOG.error("Failed to get tokens because response code is: " + response.getScope());
    }
    return null;
}
Also used : Jwt(io.jans.as.model.jwt.Jwt) AuthenticationMethod(io.jans.as.model.common.AuthenticationMethod) SignatureAlgorithm(io.jans.as.model.crypto.signature.SignatureAlgorithm) Algorithm(io.jans.as.model.jwk.Algorithm) TokenResponse(io.jans.as.client.TokenResponse) TokenRequest(io.jans.as.client.TokenRequest) OpenIdConfigurationResponse(io.jans.as.client.OpenIdConfigurationResponse) HttpException(io.jans.ca.server.HttpException) GetTokensByCodeResponse(io.jans.ca.common.response.GetTokensByCodeResponse) TokenClient(io.jans.as.client.TokenClient) Rp(io.jans.ca.server.service.Rp)

Example 4 with Algorithm

use of io.jans.as.model.jwk.Algorithm in project jans by JanssenProject.

the class KeyGeneratorService method generateKeys.

private JSONWebKeySet generateKeys(List<Algorithm> signatureAlgorithms, List<Algorithm> encryptionAlgorithms, int expiration_hours) {
    LOG.trace("Generating jwks keys...");
    JSONWebKeySet jwks = new JSONWebKeySet();
    Calendar calendar = new GregorianCalendar();
    calendar.add(Calendar.HOUR, expiration_hours);
    for (Algorithm algorithm : signatureAlgorithms) {
        try {
            SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.fromString(algorithm.name());
            JSONObject result = this.cryptoProvider.generateKey(algorithm, calendar.getTimeInMillis());
            JSONWebKey key = JSONWebKey.fromJSONObject(result);
            jwks.getKeys().add(key);
        } catch (Exception ex) {
            LOG.error(ex.getMessage(), ex);
        }
    }
    for (Algorithm algorithm : encryptionAlgorithms) {
        try {
            KeyEncryptionAlgorithm encryptionAlgorithm = KeyEncryptionAlgorithm.fromName(algorithm.getParamName());
            JSONObject result = this.cryptoProvider.generateKey(algorithm, calendar.getTimeInMillis());
            JSONWebKey key = JSONWebKey.fromJSONObject(result);
            jwks.getKeys().add(key);
        } catch (Exception ex) {
            LOG.error(ex.getMessage(), ex);
        }
    }
    // LOG.trace("jwks: ", jwks);
    LOG.trace("jwks generated successfully.");
    return jwks;
}
Also used : JSONWebKey(io.jans.as.model.jwk.JSONWebKey) JSONObject(org.json.JSONObject) JSONWebKeySet(io.jans.as.model.jwk.JSONWebKeySet) Calendar(java.util.Calendar) GregorianCalendar(java.util.GregorianCalendar) KeyEncryptionAlgorithm(io.jans.as.model.crypto.encryption.KeyEncryptionAlgorithm) GregorianCalendar(java.util.GregorianCalendar) SignatureAlgorithm(io.jans.as.model.crypto.signature.SignatureAlgorithm) SignatureAlgorithm(io.jans.as.model.crypto.signature.SignatureAlgorithm) Algorithm(io.jans.as.model.jwk.Algorithm) KeyEncryptionAlgorithm(io.jans.as.model.crypto.encryption.KeyEncryptionAlgorithm) CryptoProviderException(io.jans.as.model.exception.CryptoProviderException) HttpException(io.jans.ca.server.HttpException)

Example 5 with Algorithm

use of io.jans.as.model.jwk.Algorithm in project jans by JanssenProject.

the class KeyGeneratorService method generateKeys.

public void generateKeys() {
    List<Algorithm> signatureAlgorithms = Lists.newArrayList(Algorithm.RS256, Algorithm.RS384, Algorithm.RS512, Algorithm.ES256, Algorithm.ES384, Algorithm.ES512, Algorithm.PS256, Algorithm.PS384, Algorithm.PS512);
    List<Algorithm> encryptionAlgorithms = Lists.newArrayList(Algorithm.RSA1_5, Algorithm.RSA_OAEP);
    try {
        if (configuration.getEnableJwksGeneration()) {
            JSONWebKeySet keySet = generateKeys(signatureAlgorithms, encryptionAlgorithms, configuration.getJwksExpirationInHours());
            saveKeysInStorage(keySet.toString());
            setKeys(keySet);
        }
    } catch (Exception e) {
        LOG.error("Failed to generate json web keys.", e);
        throw new RuntimeException("Failed to generate json web keys.", e);
    }
}
Also used : JSONWebKeySet(io.jans.as.model.jwk.JSONWebKeySet) SignatureAlgorithm(io.jans.as.model.crypto.signature.SignatureAlgorithm) Algorithm(io.jans.as.model.jwk.Algorithm) KeyEncryptionAlgorithm(io.jans.as.model.crypto.encryption.KeyEncryptionAlgorithm) CryptoProviderException(io.jans.as.model.exception.CryptoProviderException) HttpException(io.jans.ca.server.HttpException)

Aggregations

SignatureAlgorithm (io.jans.as.model.crypto.signature.SignatureAlgorithm)6 Algorithm (io.jans.as.model.jwk.Algorithm)6 CryptoProviderException (io.jans.as.model.exception.CryptoProviderException)4 KeyEncryptionAlgorithm (io.jans.as.model.crypto.encryption.KeyEncryptionAlgorithm)3 JSONWebKeySet (io.jans.as.model.jwk.JSONWebKeySet)3 HttpException (io.jans.ca.server.HttpException)3 JSONObject (org.json.JSONObject)3 InvalidParameterException (io.jans.as.model.exception.InvalidParameterException)2 JSONWebKey (io.jans.as.model.jwk.JSONWebKey)2 Jwt (io.jans.as.model.jwt.Jwt)2 PublicKey (java.security.PublicKey)2 GregorianCalendar (java.util.GregorianCalendar)2 JWEAlgorithm (com.nimbusds.jose.JWEAlgorithm)1 JWSAlgorithm (com.nimbusds.jose.JWSAlgorithm)1 RSAKey (com.nimbusds.jose.jwk.RSAKey)1 OpenIdConfigurationResponse (io.jans.as.client.OpenIdConfigurationResponse)1 TokenClient (io.jans.as.client.TokenClient)1 TokenRequest (io.jans.as.client.TokenRequest)1 TokenResponse (io.jans.as.client.TokenResponse)1 AuthenticationMethod (io.jans.as.model.common.AuthenticationMethod)1