Search in sources :

Example 1 with JWEHeader

use of com.nimbusds.jose.JWEHeader 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 2 with JWEHeader

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

the class StringUtils method getDecryptedString.

/**
 * Get decrypted string
 *
 * @param type            key type
 * @param encryptedString encrypted string
 * @return decrypted string
 */
public static String getDecryptedString(@KeysManager.KeyType int type, String encryptedString) {
    KeysManager keysManager = KeysManager.getInstance();
    JWEObject jweObject;
    try {
        jweObject = JWEObject.parse(encryptedString);
        JWEHeader jweHeader = jweObject.getHeader();
        if (jweHeader.getKeyID() == null || jweHeader.getKeyID().equals(keysManager.getKeyId(type))) {
            jweObject.decrypt(new AESDecrypter(keysManager.getSecretKey(type)));
            if ("JWT".equals(jweObject.getHeader().getContentType())) {
                SignedJWT signedJwt = jweObject.getPayload().toSignedJWT();
                ECCKeyPair keyPair = keysManager.getPairForType(type);
                ECPublicKey key = null;
                if ("https://fit-pay.com".equals(signedJwt.getJWTClaimsSet().getIssuer())) {
                    key = (ECPublicKey) keysManager.getPublicKey("EC", Hex.hexStringToBytes(keyPair.getServerPublicKey()));
                } else {
                    key = (ECPublicKey) keysManager.getPublicKey("EC", Hex.hexStringToBytes(keyPair.getPublicKey()));
                }
                JWSVerifier verifier = new ECDSAVerifier(key);
                if (!signedJwt.verify(verifier)) {
                    throw new IllegalArgumentException("jwt did not pass signature validation");
                }
                return signedJwt.getJWTClaimsSet().getStringClaim("data");
            } else {
                return jweObject.getPayload().toString();
            }
        }
    } catch (Exception e) {
        FPLog.e(e);
    }
    return null;
}
Also used : ECDSAVerifier(com.nimbusds.jose.crypto.ECDSAVerifier) JWEHeader(com.nimbusds.jose.JWEHeader) ECPublicKey(java.security.interfaces.ECPublicKey) JWEObject(com.nimbusds.jose.JWEObject) JWSVerifier(com.nimbusds.jose.JWSVerifier) AESDecrypter(com.nimbusds.jose.crypto.AESDecrypter) SignedJWT(com.nimbusds.jwt.SignedJWT) ECCKeyPair(com.fitpay.android.api.models.security.ECCKeyPair) JOSEException(com.nimbusds.jose.JOSEException)

Example 3 with JWEHeader

use of com.nimbusds.jose.JWEHeader 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)

Aggregations

JOSEException (com.nimbusds.jose.JOSEException)3 JWEHeader (com.nimbusds.jose.JWEHeader)3 ECCKeyPair (com.fitpay.android.api.models.security.ECCKeyPair)2 EncryptionMethod (com.nimbusds.jose.EncryptionMethod)2 JWEAlgorithm (com.nimbusds.jose.JWEAlgorithm)2 JWEObject (com.nimbusds.jose.JWEObject)2 SignedJWT (com.nimbusds.jwt.SignedJWT)2 JWEEncrypter (com.nimbusds.jose.JWEEncrypter)1 JWSAlgorithm (com.nimbusds.jose.JWSAlgorithm)1 JWSVerifier (com.nimbusds.jose.JWSVerifier)1 Payload (com.nimbusds.jose.Payload)1 AESDecrypter (com.nimbusds.jose.crypto.AESDecrypter)1 AESEncrypter (com.nimbusds.jose.crypto.AESEncrypter)1 ECDSAVerifier (com.nimbusds.jose.crypto.ECDSAVerifier)1 EncryptedJWT (com.nimbusds.jwt.EncryptedJWT)1 JWT (com.nimbusds.jwt.JWT)1 PlainJWT (com.nimbusds.jwt.PlainJWT)1 ECPublicKey (java.security.interfaces.ECPublicKey)1 ParseException (java.text.ParseException)1 CredentialsException (org.pac4j.core.exception.CredentialsException)1