Search in sources :

Example 26 with JSONWebKey

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

the class CrossEncryptionTest method nestedJWTProducedByGluu.

@Test
public void nestedJWTProducedByGluu() throws Exception {
    AppConfiguration appConfiguration = new AppConfiguration();
    List<JSONWebKey> keyArrayList = new ArrayList<JSONWebKey>();
    keyArrayList.add(getSenderWebKey());
    JSONWebKeySet keySet = new JSONWebKeySet();
    keySet.setKeys(keyArrayList);
    final JwtSigner jwtSigner = new JwtSigner(appConfiguration, keySet, SignatureAlgorithm.RS256, "audience", null, new AbstractCryptoProvider() {

        @Override
        public JSONObject generateKey(Algorithm algorithm, Long expirationTime) throws CryptoProviderException {
            return null;
        }

        @Override
        public JSONObject generateKey(Algorithm algorithm, Long expirationTime, int keyLength) throws CryptoProviderException {
            return null;
        }

        @Override
        public boolean containsKey(String keyId) {
            return false;
        }

        @Override
        public String sign(String signingInput, String keyId, String sharedSecret, SignatureAlgorithm signatureAlgorithm) throws CryptoProviderException {
            try {
                RSAPrivateKey privateKey = ((RSAKey) JWK.parse(senderJwkJson)).toRSAPrivateKey();
                Signature signature = Signature.getInstance(signatureAlgorithm.getAlgorithm(), "BC");
                signature.initSign(privateKey);
                signature.update(signingInput.getBytes());
                return Base64Util.base64urlencode(signature.sign());
            } catch (JOSEException | ParseException | NoSuchAlgorithmException | NoSuchProviderException | InvalidKeyException | SignatureException e) {
                throw new CryptoProviderException(e);
            }
        }

        @Override
        public boolean verifySignature(String signingInput, String encodedSignature, String keyId, JSONObject jwks, String sharedSecret, SignatureAlgorithm signatureAlgorithm) throws CryptoProviderException {
            return false;
        }

        @Override
        public boolean deleteKey(String keyId) throws CryptoProviderException {
            return false;
        }

        @Override
        public PrivateKey getPrivateKey(String keyId) throws CryptoProviderException {
            throw new UnsupportedOperationException("Method not implemented.");
        }

        @Override
        public PublicKey getPublicKey(String keyId) {
            throw new UnsupportedOperationException("Method not implemented.");
        }
    });
    Jwt jwt = jwtSigner.newJwt();
    jwt.getClaims().setSubjectIdentifier("testing");
    jwt.getClaims().setIssuer("https:devgluu.saminet.local");
    jwt = jwtSigner.sign();
    RSAKey recipientPublicJWK = (RSAKey) (JWK.parse(recipientJwkJson));
    BlockEncryptionAlgorithm blockEncryptionAlgorithm = BlockEncryptionAlgorithm.A128GCM;
    KeyEncryptionAlgorithm keyEncryptionAlgorithm = KeyEncryptionAlgorithm.RSA_OAEP;
    Jwe jwe = new Jwe();
    jwe.getHeader().setType(JwtType.JWT);
    jwe.getHeader().setAlgorithm(keyEncryptionAlgorithm);
    jwe.getHeader().setEncryptionMethod(blockEncryptionAlgorithm);
    jwe.getHeader().setKeyId("1");
    jwe.setSignedJWTPayload(jwt);
    JweEncrypterImpl encrypter = new JweEncrypterImpl(keyEncryptionAlgorithm, blockEncryptionAlgorithm, recipientPublicJWK.toPublicKey());
    String jweString = encrypter.encrypt(jwe).toString();
    decryptAndValidateSignatureWithGluu(jweString);
    decryptAndValidateSignatureWithNimbus(jweString);
}
Also used : RSAKey(com.nimbusds.jose.jwk.RSAKey) RSAPrivateKey(java.security.interfaces.RSAPrivateKey) PrivateKey(java.security.PrivateKey) JSONWebKeySet(io.jans.as.model.jwk.JSONWebKeySet) ArrayList(java.util.ArrayList) SignatureAlgorithm(io.jans.as.model.crypto.signature.SignatureAlgorithm) BlockEncryptionAlgorithm(io.jans.as.model.crypto.encryption.BlockEncryptionAlgorithm) JwtSigner(io.jans.as.server.model.token.JwtSigner) AppConfiguration(io.jans.as.model.configuration.AppConfiguration) Jwe(io.jans.as.model.jwe.Jwe) AbstractCryptoProvider(io.jans.as.model.crypto.AbstractCryptoProvider) PublicKey(java.security.PublicKey) RSAPublicKey(io.jans.as.model.crypto.signature.RSAPublicKey) Jwt(io.jans.as.model.jwt.Jwt) JWEAlgorithm(com.nimbusds.jose.JWEAlgorithm) JWSAlgorithm(com.nimbusds.jose.JWSAlgorithm) KeyEncryptionAlgorithm(io.jans.as.model.crypto.encryption.KeyEncryptionAlgorithm) BlockEncryptionAlgorithm(io.jans.as.model.crypto.encryption.BlockEncryptionAlgorithm) SignatureAlgorithm(io.jans.as.model.crypto.signature.SignatureAlgorithm) Algorithm(io.jans.as.model.jwk.Algorithm) CryptoProviderException(io.jans.as.model.exception.CryptoProviderException) JSONWebKey(io.jans.as.model.jwk.JSONWebKey) JSONObject(org.json.JSONObject) Signature(java.security.Signature) KeyEncryptionAlgorithm(io.jans.as.model.crypto.encryption.KeyEncryptionAlgorithm) JweEncrypterImpl(io.jans.as.model.jwe.JweEncrypterImpl) RSAPrivateKey(java.security.interfaces.RSAPrivateKey) Test(org.testng.annotations.Test)

Example 27 with JSONWebKey

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

the class PublicOpKeyService method getPublicKey.

public PublicKey getPublicKey(String jwkSetUrl, String keyId, SignatureAlgorithm signatureAlgorithm, Use use) {
    // Get keys from cache if present
    Optional<PublicKey> cachedKey = getCachedKey(jwkSetUrl, keyId);
    if (cachedKey.isPresent()) {
        LOG.debug("Taken public key from cache. jwks_url: {}, kid : {} ", jwkSetUrl, keyId);
        return cachedKey.get();
    }
    // Request jwks from OP
    JwkClient jwkClient = opClientFactory.createJwkClient(jwkSetUrl);
    jwkClient.setExecutor(new ApacheHttpClient43Engine(httpService.getHttpClient()));
    JwkResponse jwkResponse = jwkClient.exec();
    if (jwkResponse == null || jwkResponse.getStatus() != 200) {
        LOG.error("Failed to fetch public key from OP. Obtained Response : {}", (jwkResponse == null ? jwkResponse : jwkResponse.getStatus()));
        throw new RuntimeException("Failed to fetch public key from OP. Obtained Response : " + (jwkResponse == null ? jwkResponse : jwkResponse.getStatus()));
    }
    if (!Strings.isNullOrEmpty(keyId)) {
        PublicKey publicKey = jwkResponse.getPublicKey(keyId);
        if (publicKey != null) {
            cache.put((new Pair<>(jwkSetUrl, keyId)), publicKey);
            return publicKey;
        }
    } else {
        JSONWebKeySet jsonWebKeySet = jwkResponse.getJwks();
        List<PublicKey> pks = Lists.newArrayList();
        for (JSONWebKey key : jsonWebKeySet.getKeys()) {
            if (key.getKty() == null)
                continue;
            if (signatureAlgorithm.getFamily().toString().equals(key.getKty().toString()) && (use == null || use == key.getUse())) {
                pks.add(getPublicKey(key));
            }
        }
        if (pks.size() > 1) {
            LOG.error("Multiple matching keys found in issuer's jwks_uri for algorithm : {}. `kid` must be provided in this case.", signatureAlgorithm.getName());
            throw new RuntimeException("Multiple matching keys found in issuer's jwks_uri for algorithm : " + signatureAlgorithm.getName() + ". `kid` must be provided in this case.");
        }
        if (pks.size() == 1) {
            if (!Strings.isNullOrEmpty(pks.get(0).getKeyId())) {
                cache.put((new Pair<>(jwkSetUrl, pks.get(0).getKeyId())), pks.get(0));
            }
            return pks.get(0);
        }
    }
    LOG.error("Failed to fetch public key from OP.");
    throw new RuntimeException("Failed to fetch public key from OP.");
}
Also used : JSONWebKey(io.jans.as.model.jwk.JSONWebKey) JwkResponse(io.jans.as.client.JwkResponse) JSONWebKeySet(io.jans.as.model.jwk.JSONWebKeySet) PublicKey(io.jans.as.model.crypto.PublicKey) RSAPublicKey(io.jans.as.model.crypto.signature.RSAPublicKey) ECDSAPublicKey(io.jans.as.model.crypto.signature.ECDSAPublicKey) ApacheHttpClient43Engine(org.jboss.resteasy.client.jaxrs.engines.ApacheHttpClient43Engine) JwkClient(io.jans.as.client.JwkClient) Pair(io.jans.util.Pair)

Aggregations

JSONWebKey (io.jans.as.model.jwk.JSONWebKey)27 Test (org.testng.annotations.Test)12 BaseTest (io.jans.as.client.BaseTest)11 ResponseType (io.jans.as.model.common.ResponseType)10 Parameters (org.testng.annotations.Parameters)10 TokenResponse (io.jans.as.client.TokenResponse)9 AuthCryptoProvider (io.jans.as.model.crypto.AuthCryptoProvider)9 DPoP (io.jans.as.model.jwt.DPoP)9 JSONWebKeySet (io.jans.as.model.jwk.JSONWebKeySet)6 JSONObject (org.json.JSONObject)6 RSAPublicKeyImpl (sun.security.rsa.RSAPublicKeyImpl)6 PublicKey (java.security.PublicKey)5 RSAPublicKey (io.jans.as.model.crypto.signature.RSAPublicKey)4 CryptoProviderException (io.jans.as.model.exception.CryptoProviderException)4 JwkClient (io.jans.as.client.JwkClient)3 JwkResponse (io.jans.as.client.JwkResponse)3 WebKeysConfiguration (io.jans.as.model.config.WebKeysConfiguration)3 ECDSAPublicKey (io.jans.as.model.crypto.signature.ECDSAPublicKey)3 Jwt (io.jans.as.model.jwt.Jwt)3 AuthorizationGrant (io.jans.as.server.model.common.AuthorizationGrant)3