Search in sources :

Example 1 with JWEAlgorithm

use of com.nimbusds.jose.JWEAlgorithm in project cas by apereo.

the class GenerateJwtCommand method configureJwtEncryption.

private void configureJwtEncryption(final int encryptionSecretSize, final String encryptionAlgorithm, final String encryptionMethod, final JwtGenerator<CommonProfile> g) {
    if (encryptionSecretSize <= 0 || StringUtils.isBlank(encryptionMethod) || StringUtils.isBlank(encryptionAlgorithm)) {
        LOGGER.info("No encryption algorithm or size specified, so the generated JWT will not be encrypted");
        return;
    }
    final String encryptionSecret = RandomStringUtils.randomAlphanumeric(encryptionSecretSize);
    LOGGER.info("==== Encryption Secret ====\n[{}]\n", encryptionSecret);
    final String acceptedEncAlgs = Arrays.stream(JWEAlgorithm.class.getDeclaredFields()).filter(f -> f.getType().equals(JWEAlgorithm.class)).map(Unchecked.function(f -> {
        f.setAccessible(true);
        return ((JWEAlgorithm) f.get(null)).getName();
    })).collect(Collectors.joining(","));
    LOGGER.debug("Encryption algorithm: [{}]. Available algorithms are [{}]", encryptionAlgorithm, acceptedEncAlgs);
    final String acceptedEncMethods = Arrays.stream(EncryptionMethod.class.getDeclaredFields()).filter(f -> f.getType().equals(EncryptionMethod.class)).map(Unchecked.function(f -> {
        f.setAccessible(true);
        return ((EncryptionMethod) f.get(null)).getName();
    })).collect(Collectors.joining(","));
    LOGGER.debug("Encryption method: [{}]. Available methods are [{}]", encryptionMethod, acceptedEncMethods);
    final JWEAlgorithm algorithm = JWEAlgorithm.parse(encryptionAlgorithm);
    final EncryptionMethod encryptionMethodAlg = EncryptionMethod.parse(encryptionMethod);
    if (DirectDecrypter.SUPPORTED_ALGORITHMS.contains(algorithm)) {
        if (!DirectDecrypter.SUPPORTED_ENCRYPTION_METHODS.contains(encryptionMethodAlg)) {
            LOGGER.warn("Encrypted method [{}] is not supported for algorithm [{}]. Accepted methods are [{}]", encryptionMethod, encryptionAlgorithm, DirectDecrypter.SUPPORTED_ENCRYPTION_METHODS);
            return;
        }
    }
    if (AESDecrypter.SUPPORTED_ALGORITHMS.contains(algorithm)) {
        if (!AESDecrypter.SUPPORTED_ENCRYPTION_METHODS.contains(encryptionMethodAlg)) {
            LOGGER.warn("Encrypted method [{}] is not supported for algorithm [{}]. Accepted methods are [{}]", encryptionMethod, encryptionAlgorithm, AESDecrypter.SUPPORTED_ENCRYPTION_METHODS);
            return;
        }
    }
    g.setEncryptionConfiguration(new SecretEncryptionConfiguration(encryptionSecret, algorithm, encryptionMethodAlg));
}
Also used : JWEAlgorithm(com.nimbusds.jose.JWEAlgorithm) SecretEncryptionConfiguration(org.pac4j.jwt.config.encryption.SecretEncryptionConfiguration) EncryptionMethod(com.nimbusds.jose.EncryptionMethod)

Example 2 with JWEAlgorithm

use of com.nimbusds.jose.JWEAlgorithm in project pac4j by pac4j.

the class JwtAuthenticator method validate.

@Override
public void validate(final TokenCredentials credentials, final WebContext context) {
    init();
    final String token = credentials.getToken();
    if (context != null) {
        // set the www-authenticate in case of error
        context.setResponseHeader(HttpConstants.AUTHENTICATE_HEADER, "Bearer realm=\"" + realmName + "\"");
    }
    try {
        // Parse the token
        JWT jwt = JWTParser.parse(token);
        if (jwt instanceof PlainJWT) {
            if (signatureConfigurations.isEmpty()) {
                logger.debug("JWT is not signed and no signature configurations -> verified");
            } else {
                throw new CredentialsException("A non-signed JWT cannot be accepted as signature configurations have been defined");
            }
        } else {
            SignedJWT signedJWT = null;
            if (jwt instanceof SignedJWT) {
                signedJWT = (SignedJWT) jwt;
            }
            // encrypted?
            if (jwt instanceof EncryptedJWT) {
                logger.debug("JWT is encrypted");
                final EncryptedJWT encryptedJWT = (EncryptedJWT) jwt;
                boolean found = false;
                final JWEHeader header = encryptedJWT.getHeader();
                final JWEAlgorithm algorithm = header.getAlgorithm();
                final EncryptionMethod method = header.getEncryptionMethod();
                for (final EncryptionConfiguration config : encryptionConfigurations) {
                    if (config.supports(algorithm, method)) {
                        logger.debug("Using encryption configuration: {}", config);
                        try {
                            config.decrypt(encryptedJWT);
                            signedJWT = encryptedJWT.getPayload().toSignedJWT();
                            if (signedJWT != null) {
                                jwt = signedJWT;
                            }
                            found = true;
                            break;
                        } catch (final JOSEException e) {
                            logger.debug("Decryption fails with encryption configuration: {}, passing to the next one", config);
                        }
                    }
                }
                if (!found) {
                    throw new CredentialsException("No encryption algorithm found for JWT: " + token);
                }
            }
            // signed?
            if (signedJWT != null) {
                logger.debug("JWT is signed");
                boolean verified = false;
                boolean found = false;
                final JWSAlgorithm algorithm = signedJWT.getHeader().getAlgorithm();
                for (final SignatureConfiguration config : signatureConfigurations) {
                    if (config.supports(algorithm)) {
                        logger.debug("Using signature configuration: {}", config);
                        try {
                            verified = config.verify(signedJWT);
                            found = true;
                            if (verified) {
                                break;
                            }
                        } catch (final JOSEException e) {
                            logger.debug("Verification fails with signature configuration: {}, passing to the next one", config);
                        }
                    }
                }
                if (!found) {
                    throw new CredentialsException("No signature algorithm found for JWT: " + token);
                }
                if (!verified) {
                    throw new CredentialsException("JWT verification failed: " + token);
                }
            }
        }
        createJwtProfile(credentials, jwt);
    } catch (final ParseException e) {
        throw new CredentialsException("Cannot decrypt / verify JWT", e);
    }
}
Also used : PlainJWT(com.nimbusds.jwt.PlainJWT) SignatureConfiguration(org.pac4j.jwt.config.signature.SignatureConfiguration) EncryptionConfiguration(org.pac4j.jwt.config.encryption.EncryptionConfiguration) PlainJWT(com.nimbusds.jwt.PlainJWT) JWT(com.nimbusds.jwt.JWT) SignedJWT(com.nimbusds.jwt.SignedJWT) EncryptedJWT(com.nimbusds.jwt.EncryptedJWT) SignedJWT(com.nimbusds.jwt.SignedJWT) EncryptionMethod(com.nimbusds.jose.EncryptionMethod) CredentialsException(org.pac4j.core.exception.CredentialsException) JWSAlgorithm(com.nimbusds.jose.JWSAlgorithm) JWEHeader(com.nimbusds.jose.JWEHeader) JWEAlgorithm(com.nimbusds.jose.JWEAlgorithm) ParseException(java.text.ParseException) EncryptedJWT(com.nimbusds.jwt.EncryptedJWT) JOSEException(com.nimbusds.jose.JOSEException)

Example 3 with JWEAlgorithm

use of com.nimbusds.jose.JWEAlgorithm in project fitpay-android-sdk by fitpay.

the class StringUtils method getEncryptedString.

/**
 * Get encrypted string
 *
 * @param type            key type
 * @param decryptedString decrypted string
 * @return encrypted string
 */
public static String getEncryptedString(@KeysManager.KeyType int type, String decryptedString) {
    JWEAlgorithm alg = JWEAlgorithm.A256GCMKW;
    EncryptionMethod enc = EncryptionMethod.A256GCM;
    ECCKeyPair keyPair = KeysManager.getInstance().getPairForType(type);
    if (null == keyPair) {
        throw new IllegalStateException("No key pair available for type (type = " + type + ")");
    }
    JWEHeader.Builder jweHeaderBuilder = new JWEHeader.Builder(alg, enc).contentType("application/json").keyID(keyPair.getKeyId());
    JWEHeader header = jweHeaderBuilder.build();
    Payload payload = new Payload(decryptedString);
    JWEObject jweObject = new JWEObject(header, payload);
    try {
        JWEEncrypter encrypter = new AESEncrypter(KeysManager.getInstance().getSecretKey(type));
        jweObject.encrypt(encrypter);
    } catch (JOSEException e) {
        FPLog.e(e);
    }
    return jweObject.serialize();
}
Also used : AESEncrypter(com.nimbusds.jose.crypto.AESEncrypter) JWEHeader(com.nimbusds.jose.JWEHeader) JWEObject(com.nimbusds.jose.JWEObject) JWEAlgorithm(com.nimbusds.jose.JWEAlgorithm) Payload(com.nimbusds.jose.Payload) JWEEncrypter(com.nimbusds.jose.JWEEncrypter) EncryptionMethod(com.nimbusds.jose.EncryptionMethod) ECCKeyPair(com.fitpay.android.api.models.security.ECCKeyPair) JOSEException(com.nimbusds.jose.JOSEException)

Example 4 with JWEAlgorithm

use of com.nimbusds.jose.JWEAlgorithm in project cas by apereo.

the class GenerateJwtCommand method configureJwtEncryption.

private static void configureJwtEncryption(final int encryptionSecretSize, final String encryptionAlgorithm, final String encryptionMethod, final JwtGenerator g) {
    if (encryptionSecretSize <= 0 || StringUtils.isBlank(encryptionMethod) || StringUtils.isBlank(encryptionAlgorithm)) {
        LOGGER.info("No encryption algorithm or size specified, so the generated JWT will not be encrypted");
        return;
    }
    val encryptionSecret = RandomUtils.randomAlphanumeric(encryptionSecretSize);
    LOGGER.info("==== Encryption Secret ====\n[{}]\n", encryptionSecret);
    val acceptedEncAlgs = Arrays.stream(JWEAlgorithm.class.getDeclaredFields()).filter(f -> f.getType().equals(JWEAlgorithm.class)).map(Unchecked.function(f -> {
        f.setAccessible(true);
        return ((JWEAlgorithm) f.get(null)).getName();
    })).collect(Collectors.joining(","));
    LOGGER.debug("Encryption algorithm: [{}]. Available algorithms are [{}]", encryptionAlgorithm, acceptedEncAlgs);
    val acceptedEncMethods = Arrays.stream(EncryptionMethod.class.getDeclaredFields()).filter(f -> f.getType().equals(EncryptionMethod.class)).map(Unchecked.function(f -> {
        f.setAccessible(true);
        return ((EncryptionMethod) f.get(null)).getName();
    })).collect(Collectors.joining(","));
    LOGGER.debug("Encryption method: [{}]. Available methods are [{}]", encryptionMethod, acceptedEncMethods);
    val algorithm = JWEAlgorithm.parse(encryptionAlgorithm);
    val encryptionMethodAlg = EncryptionMethod.parse(encryptionMethod);
    if (DirectDecrypter.SUPPORTED_ALGORITHMS.contains(algorithm)) {
        if (!DirectDecrypter.SUPPORTED_ENCRYPTION_METHODS.contains(encryptionMethodAlg)) {
            LOGGER.warn("Encrypted method [{}] is not supported for algorithm [{}]. Accepted methods are [{}]", encryptionMethod, encryptionAlgorithm, DirectDecrypter.SUPPORTED_ENCRYPTION_METHODS);
            return;
        }
    }
    if (AESDecrypter.SUPPORTED_ALGORITHMS.contains(algorithm)) {
        if (!AESDecrypter.SUPPORTED_ENCRYPTION_METHODS.contains(encryptionMethodAlg)) {
            LOGGER.warn("Encrypted method [{}] is not supported for algorithm [{}]. Accepted methods are [{}]", encryptionMethod, encryptionAlgorithm, AESDecrypter.SUPPORTED_ENCRYPTION_METHODS);
            return;
        }
    }
    g.setEncryptionConfiguration(new SecretEncryptionConfiguration(encryptionSecret, algorithm, encryptionMethodAlg));
}
Also used : lombok.val(lombok.val) JWEAlgorithm(com.nimbusds.jose.JWEAlgorithm) SecretEncryptionConfiguration(org.pac4j.jwt.config.encryption.SecretEncryptionConfiguration) EncryptionMethod(com.nimbusds.jose.EncryptionMethod)

Aggregations

EncryptionMethod (com.nimbusds.jose.EncryptionMethod)4 JWEAlgorithm (com.nimbusds.jose.JWEAlgorithm)4 JOSEException (com.nimbusds.jose.JOSEException)2 JWEHeader (com.nimbusds.jose.JWEHeader)2 SecretEncryptionConfiguration (org.pac4j.jwt.config.encryption.SecretEncryptionConfiguration)2 ECCKeyPair (com.fitpay.android.api.models.security.ECCKeyPair)1 JWEEncrypter (com.nimbusds.jose.JWEEncrypter)1 JWEObject (com.nimbusds.jose.JWEObject)1 JWSAlgorithm (com.nimbusds.jose.JWSAlgorithm)1 Payload (com.nimbusds.jose.Payload)1 AESEncrypter (com.nimbusds.jose.crypto.AESEncrypter)1 EncryptedJWT (com.nimbusds.jwt.EncryptedJWT)1 JWT (com.nimbusds.jwt.JWT)1 PlainJWT (com.nimbusds.jwt.PlainJWT)1 SignedJWT (com.nimbusds.jwt.SignedJWT)1 ParseException (java.text.ParseException)1 lombok.val (lombok.val)1 CredentialsException (org.pac4j.core.exception.CredentialsException)1 EncryptionConfiguration (org.pac4j.jwt.config.encryption.EncryptionConfiguration)1 SignatureConfiguration (org.pac4j.jwt.config.signature.SignatureConfiguration)1