org.apache.cxf.rs.security.jose.jwk.JsonWebKey Java Examples

The following examples show how to use org.apache.cxf.rs.security.jose.jwk.JsonWebKey. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ApacheCXFConsumer.java    From cxf with Apache License 2.0 6 votes vote down vote up
protected void consumeCompactJWE(String encryptedData, String plainText, JsonWebKeys keys) {

        // Decrypt

        // 1. Read data to get key id (only need to do this if you don't know the key)
        JweCompactConsumer jweConsumer = new JweCompactConsumer(encryptedData);
        String kid = jweConsumer.getJweHeaders().getKeyId();

        Assert.assertNotNull("Data does not contain kid header.", kid);

        // 2. Get key
        JsonWebKey key = keys.getKey(kid);
        Assert.assertNotNull("Data encrypted with unknown key", key);

        // 3. decrypt
        JweDecryptionProvider decryptor = getJweDecryptionProvider(key,
            jweConsumer.getJweHeaders().getKeyEncryptionAlgorithm(),
            jweConsumer.getJweHeaders().getContentEncryptionAlgorithm());
        String decryptedText = decryptor.decrypt(encryptedData).getContentText();

        // Validate plain text
        Assert.assertEquals(plainText, decryptedText);
    }
 
Example #2
Source File: JweUtils.java    From cxf with Apache License 2.0 6 votes vote down vote up
public static KeyEncryptionProvider getKeyEncryptionProvider(JsonWebKey jwk, KeyAlgorithm defaultAlgorithm) {
    KeyAlgorithm keyAlgo = jwk.getAlgorithm() == null ? defaultAlgorithm
        : KeyAlgorithm.getAlgorithm(jwk.getAlgorithm());
    KeyEncryptionProvider keyEncryptionProvider = null;
    KeyType keyType = jwk.getKeyType();
    if (KeyType.RSA == keyType) {
        keyEncryptionProvider = getPublicKeyEncryptionProvider(JwkUtils.toRSAPublicKey(jwk, true),
                                                             keyAlgo);
    } else if (KeyType.OCTET == keyType) {
        keyEncryptionProvider = getSecretKeyEncryptionAlgorithm(JwkUtils.toSecretKey(jwk, keyAlgo),
                                                                keyAlgo);
    } else if (keyAlgo == KeyAlgorithm.ECDH_ES_DIRECT) {
        return new EcdhDirectKeyEncryptionAlgorithm();
    } else {
        ContentAlgorithm ctAlgo = null;
        Message m = PhaseInterceptorChain.getCurrentMessage();
        if (m != null) {
            ctAlgo = getContentAlgo((String)m.get(JoseConstants.RSSEC_ENCRYPTION_CONTENT_ALGORITHM));
        }
        keyEncryptionProvider = new EcdhAesWrapKeyEncryptionAlgorithm(JwkUtils.toECPublicKey(jwk),
                                    jwk.getStringProperty(JsonWebKey.EC_CURVE),
                                    keyAlgo,
                                    ctAlgo == null ? ContentAlgorithm.A128GCM : ctAlgo);
    }
    return keyEncryptionProvider;
}
 
Example #3
Source File: OIDCKeysServiceTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@org.junit.Test
public void testGetRSAPublicKey() throws Exception {
    URL busFile = OIDCFlowTest.class.getResource("client.xml");

    String address = "https://localhost:" + JCACHE_SERVER.getPort() + "/services/";
    WebClient client = WebClient.create(address, OAuth2TestUtils.setupProviders(),
                                        "alice", "security", busFile.toString());
    client.accept("application/json");

    client.path("keys/");
    Response response = client.get();
    JsonWebKeys jsonWebKeys = response.readEntity(JsonWebKeys.class);

    assertEquals(1, jsonWebKeys.getKeys().size());

    JsonWebKey jsonWebKey = jsonWebKeys.getKeys().get(0);
    assertEquals(KeyType.RSA, jsonWebKey.getKeyType());
    assertEquals("alice", jsonWebKey.getKeyId());
    assertNotNull(jsonWebKey.getProperty("n"));
    assertNotNull(jsonWebKey.getProperty("e"));
    // Check we don't send the private key back
    checkPrivateKeyParametersNotPresent(jsonWebKeys);
}
 
Example #4
Source File: ApacheCXFConsumer.java    From cxf with Apache License 2.0 6 votes vote down vote up
protected void consumeJsonJWE(String encryptedData, String plainText, JsonWebKeys keys) {

        // Decrypt

        // 1. Read data
        JweJsonConsumer jweConsumer = new JweJsonConsumer(encryptedData);
        jweConsumer.getRecipients().forEach(encryptionBlock -> {
            String kid = Crypto.findKeyId(jweConsumer, encryptionBlock);
            Assert.assertNotNull("Data does not contain kid header.", kid);

            // 2. Get Key
            JsonWebKey key = keys.getKey(kid);
            Assert.assertNotNull("Data encrypted with unknown key", key);

            // 3. Decrypt
            KeyAlgorithm keyAlgo = Crypto.findKeyAlgorithm(jweConsumer, encryptionBlock);
            ContentAlgorithm contentAlgo = Crypto.findContentAlgorithm(jweConsumer, encryptionBlock);
            Assert.assertNotNull("Encrypted data does not define algorithm used", contentAlgo);
            JweDecryptionProvider decryptor = getJweDecryptionProvider(key, keyAlgo, contentAlgo);
            JweDecryptionOutput output = jweConsumer.decryptWith(decryptor, encryptionBlock);

            // Validate plain text
            String payload = output.getContentText();
            Assert.assertEquals(plainText, payload);
        });
    }
 
Example #5
Source File: JweUtils.java    From cxf with Apache License 2.0 6 votes vote down vote up
public static KeyDecryptionProvider getKeyDecryptionProvider(JsonWebKey jwk, KeyAlgorithm defaultAlgorithm) {
    KeyAlgorithm keyAlgo = jwk.getAlgorithm() == null ? defaultAlgorithm
        : KeyAlgorithm.getAlgorithm(jwk.getAlgorithm());
    KeyDecryptionProvider keyDecryptionProvider = null;
    KeyType keyType = jwk.getKeyType();
    if (KeyType.RSA == keyType) {
        keyDecryptionProvider = getPrivateKeyDecryptionProvider(JwkUtils.toRSAPrivateKey(jwk),
                                                             keyAlgo);
    } else if (KeyType.OCTET == keyType) {
        keyDecryptionProvider = getSecretKeyDecryptionProvider(JwkUtils.toSecretKey(jwk),
                                        keyAlgo);
    } else {
        keyDecryptionProvider = getPrivateKeyDecryptionProvider(JwkUtils.toECPrivateKey(jwk),
                                                                 keyAlgo);
    }
    return keyDecryptionProvider;
}
 
Example #6
Source File: OIDCKeysServiceTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@org.junit.Test
public void testGetJWKRSAPublicKey() throws Exception {
    URL busFile = OIDCFlowTest.class.getResource("client.xml");

    String address = "https://localhost:" + JCACHE_SERVER.getPort() + "/services2/";
    WebClient client = WebClient.create(address, OAuth2TestUtils.setupProviders(),
                                        "alice", "security", busFile.toString());
    client.accept("application/json");

    client.path("keys/");
    Response response = client.get();
    JsonWebKeys jsonWebKeys = response.readEntity(JsonWebKeys.class);

    assertEquals(1, jsonWebKeys.getKeys().size());

    JsonWebKey jsonWebKey = jsonWebKeys.getKeys().get(0);
    assertEquals(KeyType.RSA, jsonWebKey.getKeyType());
    assertEquals("2011-04-29", jsonWebKey.getKeyId());
    assertNotNull(jsonWebKey.getProperty("n"));
    assertNotNull(jsonWebKey.getProperty("e"));
    // Check we don't send the private key back
    checkPrivateKeyParametersNotPresent(jsonWebKeys);
}
 
Example #7
Source File: OIDCKeysServiceTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@org.junit.Test
public void testGetJWKECPublicKey() throws Exception {
    URL busFile = OIDCFlowTest.class.getResource("client.xml");

    String address = "https://localhost:" + JCACHE_SERVER.getPort() + "/services3/";
    WebClient client = WebClient.create(address, OAuth2TestUtils.setupProviders(),
                                        "alice", "security", busFile.toString());
    client.accept("application/json");

    client.path("keys/");
    Response response = client.get();
    JsonWebKeys jsonWebKeys = response.readEntity(JsonWebKeys.class);

    assertEquals(1, jsonWebKeys.getKeys().size());

    JsonWebKey jsonWebKey = jsonWebKeys.getKeys().get(0);
    assertEquals(KeyType.EC, jsonWebKey.getKeyType());
    assertEquals("ECKey", jsonWebKey.getKeyId());
    assertNotNull(jsonWebKey.getProperty("x"));
    assertNotNull(jsonWebKey.getProperty("y"));
    // Check we don't send the private key back
    checkPrivateKeyParametersNotPresent(jsonWebKeys);
}
 
Example #8
Source File: JweCompactReaderWriterTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Test
public void testECDHESDirectKeyEncryption() throws Exception {
    ECPrivateKey bobPrivateKey =
        CryptoUtils.getECPrivateKey(JsonWebKey.EC_CURVE_P256,
                                    "VEmDZpDXXK8p8N0Cndsxs924q6nS1RXFASRl6BfUqdw");

    final ECPublicKey bobPublicKey =
        CryptoUtils.getECPublicKey(JsonWebKey.EC_CURVE_P256,
                                   "weNJy2HscCSM6AEDTDg04biOvhFhyyWvOHQfeF_PxMQ",
                                   "e8lnCO-AlStT-NJVX-crhB7QRYhiix03illJOVAOyck");
    JweEncryptionProvider jweOut =
        new EcdhDirectKeyJweEncryption(bobPublicKey,
                                       JsonWebKey.EC_CURVE_P256,
                                       "Alice",
                                       "Bob",
                                       ContentAlgorithm.A128GCM);

    String jweOutput = jweOut.encrypt("Hello".getBytes(), null);
    JweDecryptionProvider jweIn =
        new EcdhDirectKeyJweDecryption(bobPrivateKey, ContentAlgorithm.A128GCM);
    assertEquals("Hello", jweIn.decrypt(jweOutput).getContentText());
}
 
Example #9
Source File: JwsJwksJwtAccessTokenValidator.java    From cxf with Apache License 2.0 6 votes vote down vote up
private JwkHolder updateJwk(String keyId) {
    Objects.requireNonNull(jwksURL, "JWK Set URL must be specified");
    JwkHolder jwkHolder = null;
    final Set<String> kids = new HashSet<>();
    for (JsonWebKey jwk : getJsonWebKeys().getKeys()) {
        if (PublicKeyUse.ENCRYPT != jwk.getPublicKeyUse()) {
            final String kid = jwk.getKeyId();
            kids.add(kid);
            final JwkHolder h = new JwkHolder(jwk);
            if (keyId.equals(kid)) {
                jwkHolder = h;
            } else {
                jsonWebKeys.putIfAbsent(kid, h);
            }
        }
    }
    jsonWebKeys.keySet().removeIf(not(kids::contains));
    return jwkHolder;
}
 
Example #10
Source File: TestJwk.java    From deprecated-security-advanced-modules with Apache License 2.0 6 votes vote down vote up
private static JsonWebKey createRsa(String keyId, String algorithm, String e, String n, String d) {
	JsonWebKey result = new JsonWebKey();

	result.setKeyId(keyId);
	result.setKeyType(KeyType.RSA);
	result.setAlgorithm(algorithm);
	result.setPublicKeyUse(PublicKeyUse.SIGN);

	if (d != null) {
		result.setProperty("d", d);
	}

	result.setProperty("e", e);
	result.setProperty("n", n);

	return result;
}
 
Example #11
Source File: JwsJsonConsumerTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Test
public void testVerifySingleEntryInDualSignedDocument() throws Exception {
    JwsJsonConsumer consumer = new JwsJsonConsumer(DUAL_SIGNED_DOCUMENT);
    JsonWebKeys jwks = readKeySet("jwkPublicJsonConsumerSet.txt");

    List<JwsJsonSignatureEntry> sigEntries = consumer.getSignatureEntries();
    assertEquals(2, sigEntries.size());
    // 1st signature
    String firstKid = sigEntries.get(0).getKeyId();
    assertEquals(KID_OF_THE_FIRST_SIGNER, firstKid);
    JsonWebKey rsaKey = jwks.getKey(firstKid);
    assertNotNull(rsaKey);
    JwsSignatureVerifier jws = JwsUtils.getSignatureVerifier(rsaKey);
    assertTrue(consumer.verifySignatureWith(jws));
    List<JwsJsonSignatureEntry> remainingEntries =
        consumer.verifyAndGetNonValidated(Collections.singletonList(jws));
    assertEquals(1, remainingEntries.size());
    assertEquals(KID_OF_THE_SECOND_SIGNER, remainingEntries.get(0).getKeyId());

}
 
Example #12
Source File: ApacheCXFProducer.java    From cxf with Apache License 2.0 6 votes vote down vote up
public void produceJWS(String keyType, String signatureAlgorithm, Serialization serialization, String plainText,
    String jwksJson) {
    JsonWebKeys keys = JwkUtils.readJwkSet(jwksJson);
    JsonWebKey key = getRequestedKeyType(keyType, keys).orElseThrow(IllegalArgumentException::new);

    // Sign
    JwsHeaders jwsHeaders = new JwsHeaders();
    jwsHeaders.setKeyId(key.getKeyId());
    jwsHeaders.setAlgorithm(signatureAlgorithm);
    switch (serialization) {
    case COMPACT:
        produceCompactJWS(plainText, key, jwsHeaders);
        break;
    case FLATTENED:
        produceJsonJWS(plainText, key, jwsHeaders, true);
        break;
    case JSON:
        produceJsonJWS(plainText, key, jwsHeaders, false);
        break;
    default:
        throw new IllegalArgumentException("Serialization not supported: " + serialization);
    }

}
 
Example #13
Source File: JwsUtilsTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Test
public void testLoadVerificationKeyWithCert() throws Exception {
    Properties p = new Properties();
    p.put(JoseConstants.RSSEC_KEY_STORE_FILE,
        "org/apache/cxf/rs/security/jose/jws/alice.jks");
    p.put(JoseConstants.RSSEC_KEY_STORE_PSWD, "password");
    p.put(JoseConstants.RSSEC_KEY_STORE_ALIAS, "alice");
    p.put(JoseConstants.RSSEC_SIGNATURE_INCLUDE_CERT, true);
    JsonWebKeys keySet = JwsUtils.loadPublicVerificationKeys(createMessage(), p, true);
    assertEquals(1, keySet.asMap().size());
    List<JsonWebKey> keys = keySet.getRsaKeys();
    assertEquals(1, keys.size());
    JsonWebKey key = keys.get(0);
    assertEquals(KeyType.RSA, key.getKeyType());
    assertEquals("alice", key.getKeyId());
    assertNotNull(key.getKeyProperty(JsonWebKey.RSA_PUBLIC_EXP));
    assertNotNull(key.getKeyProperty(JsonWebKey.RSA_MODULUS));
    assertNull(key.getKeyProperty(JsonWebKey.RSA_PRIVATE_EXP));
    List<String> chain = key.getX509Chain();
    assertNotNull(chain);
    assertEquals(2, chain.size());
}
 
Example #14
Source File: JwsCompactReaderWriterTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Test
public void testReadJwsWithJwkSignedByMac() throws Exception {
    JwsJwtCompactConsumer jws = new JwsJwtCompactConsumer(ENCODED_TOKEN_WITH_JSON_KEY_SIGNED_BY_MAC);
    assertTrue(jws.verifySignatureWith(new HmacJwsSignatureVerifier(ENCODED_MAC_KEY,
                                                                    SignatureAlgorithm.HS256)));
    JwtToken token = jws.getJwtToken();
    JwsHeaders headers = new JwsHeaders(token.getJwsHeaders());
    assertEquals(JoseType.JWT, headers.getType());
    assertEquals(SignatureAlgorithm.HS256, headers.getSignatureAlgorithm());

    JsonWebKey key = headers.getJsonWebKey();
    assertEquals(KeyType.OCTET, key.getKeyType());
    List<KeyOperation> keyOps = key.getKeyOperation();
    assertEquals(2, keyOps.size());
    assertEquals(KeyOperation.SIGN, keyOps.get(0));
    assertEquals(KeyOperation.VERIFY, keyOps.get(1));

    validateSpecClaim(token.getClaims());
}
 
Example #15
Source File: JwsUtils.java    From cxf with Apache License 2.0 6 votes vote down vote up
public static JsonWebKeys loadPublicVerificationKeys(Message m, Properties props, boolean stripPrivateParameters) {
    String storeType = props.getProperty(JoseConstants.RSSEC_KEY_STORE_TYPE);
    if ("jwk".equals(storeType)) {
        List<JsonWebKey> jsonWebKeys = JwkUtils.loadJsonWebKeys(m, props, KeyOperation.SIGN, null);
        if (jsonWebKeys == null || jsonWebKeys.isEmpty()) {
            throw new JoseException("Error loading keys");
        }
        return new JsonWebKeys(stripPrivateParameters ? JwkUtils.stripPrivateParameters(jsonWebKeys) : jsonWebKeys);
    }
    X509Certificate[] certs = null;
    if (PropertyUtils.isTrue(props.get(JoseConstants.RSSEC_SIGNATURE_INCLUDE_CERT))) {
        certs = KeyManagementUtils.loadX509CertificateOrChain(m, props);
    }
    PublicKey key = certs != null && certs.length > 0
        ? certs[0].getPublicKey() : KeyManagementUtils.loadPublicKey(m, props);
    JsonWebKey jwk = JwkUtils.fromPublicKey(key, props, JoseConstants.RSSEC_SIGNATURE_ALGORITHM);
    jwk.setPublicKeyUse(PublicKeyUse.SIGN);
    if (certs != null) {
        jwk.setX509Chain(KeyManagementUtils.encodeX509CertificateChain(certs));
    }
    return new JsonWebKeys(jwk);
}
 
Example #16
Source File: JwsJsonConsumerTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Test
public void testVerifyDualSignedDocument() throws Exception {
    JwsJsonConsumer consumer = new JwsJsonConsumer(DUAL_SIGNED_DOCUMENT);
    JsonWebKeys jwks = readKeySet("jwkPublicJsonConsumerSet.txt");

    List<JwsJsonSignatureEntry> sigEntries = consumer.getSignatureEntries();
    assertEquals(2, sigEntries.size());
    // 1st signature
    String firstKid = sigEntries.get(0).getKeyId();
    assertEquals(KID_OF_THE_FIRST_SIGNER, firstKid);
    JsonWebKey rsaKey = jwks.getKey(firstKid);
    assertNotNull(rsaKey);
    assertTrue(sigEntries.get(0).verifySignatureWith(rsaKey));
    // 2nd signature
    String secondKid = sigEntries.get(1).getKeyId();
    assertEquals(KID_OF_THE_SECOND_SIGNER, secondKid);
    JsonWebKey ecKey = jwks.getKey(secondKid);
    assertNotNull(ecKey);
    assertTrue(sigEntries.get(1).verifySignatureWith(ecKey));
}
 
Example #17
Source File: ApacheCXFConsumer.java    From cxf with Apache License 2.0 6 votes vote down vote up
private JweDecryptionProvider getJweDecryptionProvider(JsonWebKey key, KeyAlgorithm keyEncryptionAlgorithm,
    ContentAlgorithm contentEncryptionAlgorithm) {
    if (key.getAlgorithm() != null) {
        return JweUtils.createJweDecryptionProvider(key, contentEncryptionAlgorithm);
    }
    switch (key.getKeyType()) {
    case EC:
        return JweUtils.createJweDecryptionProvider(JwkUtils.toECPrivateKey(key), keyEncryptionAlgorithm,
            contentEncryptionAlgorithm);
    case RSA:
        return JweUtils.createJweDecryptionProvider(JwkUtils.toRSAPrivateKey(key), keyEncryptionAlgorithm,
            contentEncryptionAlgorithm);
    case OCTET:
        SecretKey secretKey = CryptoUtils.createSecretKeySpec(
            (String) key.getProperty(JsonWebKey.OCTET_KEY_VALUE), keyEncryptionAlgorithm.getJavaName());
        return JweUtils.createJweDecryptionProvider(secretKey, keyEncryptionAlgorithm,
            contentEncryptionAlgorithm);
    default:
        throw new IllegalArgumentException("JWK KeyType not supported: " + key.getKeyType());
    }
}
 
Example #18
Source File: EcdhDirectKeyDecryptionAlgorithm.java    From cxf with Apache License 2.0 5 votes vote down vote up
protected byte[] getDecryptedContentEncryptionKeyFromHeaders(JweHeaders headers, ECPrivateKey key) {
    ContentAlgorithm jwtAlgo = headers.getContentEncryptionAlgorithm();
    JsonWebKey publicJwk = headers.getJsonWebKey("epk");
    String apuHeader = (String) headers.getHeader("apu");
    byte[] apuBytes = apuHeader == null ? null : JoseUtils.decode(apuHeader);
    String apvHeader = (String) headers.getHeader("apv");
    byte[] apvBytes = apvHeader == null ? null : JoseUtils.decode(apvHeader);
    return JweUtils.getECDHKey(key, JwkUtils.toECPublicKey(publicJwk), apuBytes, apvBytes,
        jwtAlgo.getJwaName(), jwtAlgo.getKeySizeBits());
}
 
Example #19
Source File: JwsCompactReaderWriterTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testWriteJwsWithJwkAsMapSignedByMac() throws Exception {
    Map<String, Object> map = new LinkedHashMap<>();
    map.put(JsonWebKey.KEY_TYPE, JsonWebKey.KEY_TYPE_OCTET);
    map.put(JsonWebKey.KEY_OPERATIONS,
            new KeyOperation[]{KeyOperation.SIGN, KeyOperation.VERIFY});
    doTestWriteJwsWithJwkSignedByMac(map);
}
 
Example #20
Source File: JwsJoseCookBookTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testProtectingSpecificHeaderFieldsSignature() throws Exception {
    JwsJsonProducer jsonProducer = new JwsJsonProducer(PAYLOAD);
    assertEquals(jsonProducer.getPlainPayload(), PAYLOAD);
    assertEquals(jsonProducer.getUnsignedEncodedPayload(), ENCODED_PAYLOAD);
    JwsHeaders protectedHeader = new JwsHeaders();
    protectedHeader.setSignatureAlgorithm(SignatureAlgorithm.HS256);
    JwsHeaders unprotectedHeader = new JwsHeaders();
    unprotectedHeader.setKeyId(HMAC_KID_VALUE);
    JsonWebKeys jwks = readKeySet("cookbookSecretSet.txt");
    List<JsonWebKey> keys = jwks.getKeys();
    JsonWebKey key = keys.get(0);
    jsonProducer.signWith(JwsUtils.getSignatureProvider(key, SignatureAlgorithm.HS256),
            protectedHeader, unprotectedHeader);
    assertEquals(jsonProducer.getJwsJsonSignedDocument(),
            PROTECTING_SPECIFIC_HEADER_FIELDS_JSON_GENERAL_SERIALIZATION);
    JwsJsonConsumer jsonConsumer =
            new JwsJsonConsumer(jsonProducer.getJwsJsonSignedDocument());
    assertTrue(jsonConsumer.verifySignatureWith(key, SignatureAlgorithm.HS256));

    jsonProducer = new JwsJsonProducer(PAYLOAD, true);
    jsonProducer.signWith(JwsUtils.getSignatureProvider(key, SignatureAlgorithm.HS256),
            protectedHeader, unprotectedHeader);
    assertEquals(jsonProducer.getJwsJsonSignedDocument(),
            PROTECTING_SPECIFIC_HEADER_FIELDS_JSON_FLATTENED_SERIALIZATION);
    jsonConsumer = new JwsJsonConsumer(jsonProducer.getJwsJsonSignedDocument());
    assertTrue(jsonConsumer.verifySignatureWith(key, SignatureAlgorithm.HS256));
}
 
Example #21
Source File: JwsUtils.java    From cxf with Apache License 2.0 5 votes vote down vote up
private static SignatureAlgorithm getDefaultKeyAlgorithm(JsonWebKey jwk) {
    KeyType keyType = jwk.getKeyType();
    if (KeyType.OCTET == keyType) {
        return SignatureAlgorithm.HS256;
    } else if (KeyType.EC == keyType) {
        return SignatureAlgorithm.ES256;
    } else {
        return SignatureAlgorithm.RS256;
    }
}
 
Example #22
Source File: JwsUtils.java    From cxf with Apache License 2.0 5 votes vote down vote up
public static JwsSignatureVerifier getSignatureVerifier(JsonWebKey jwk, SignatureAlgorithm defaultAlgorithm) {
    SignatureAlgorithm sigAlgo = jwk.getAlgorithm() == null ? defaultAlgorithm
        : SignatureAlgorithm.getAlgorithm(jwk.getAlgorithm());
    JwsSignatureVerifier theVerifier = null;
    KeyType keyType = jwk.getKeyType();
    if (KeyType.RSA == keyType) {
        theVerifier = getPublicKeySignatureVerifier(JwkUtils.toRSAPublicKey(jwk, true), sigAlgo);
    } else if (KeyType.OCTET == keyType) {
        byte[] key = JoseUtils.decode((String)jwk.getProperty(JsonWebKey.OCTET_KEY_VALUE));
        theVerifier = getHmacSignatureVerifier(key, sigAlgo);
    } else if (KeyType.EC == keyType) {
        theVerifier = getPublicKeySignatureVerifier(JwkUtils.toECPublicKey(jwk), sigAlgo);
    }
    return theVerifier;
}
 
Example #23
Source File: SelfRefreshingKeySet.java    From deprecated-security-advanced-modules with Apache License 2.0 5 votes vote down vote up
public synchronized JsonWebKey getKeyAfterRefresh(String kid)
		throws AuthenticatorUnavailableException, BadCredentialsException {
	JsonWebKey result = getKeyAfterRefreshInternal(kid);

	if (result != null) {
		return result;
	} else if (jsonWebKeys.getKeys().size() == 0) {
		throw new AuthenticatorUnavailableException("No JWK are available from IdP");
	} else {
		throw new BadCredentialsException("JWT did not contain KID which is required if IdP provides multiple JWK");
	}
}
 
Example #24
Source File: JoseHeaders.java    From cxf with Apache License 2.0 5 votes vote down vote up
public JsonWebKey getJsonWebKey(String headerName) {
    Object jsonWebKey = getHeader(headerName);
    if (jsonWebKey == null || jsonWebKey instanceof JsonWebKey) {
        return (JsonWebKey)jsonWebKey;
    }
    Map<String, Object> map = CastUtils.cast((Map<?, ?>)jsonWebKey);
    return new JsonWebKey(map);
}
 
Example #25
Source File: JweUtils.java    From cxf with Apache License 2.0 5 votes vote down vote up
private static KeyAlgorithm getDefaultKeyAlgorithm(JsonWebKey jwk) {
    KeyType keyType = jwk.getKeyType();
    if (KeyType.OCTET == keyType) {
        return KeyAlgorithm.A128GCMKW;
    } else if (KeyType.RSA == keyType) {
        return KeyAlgorithm.RSA_OAEP;
    } else {
        return KeyAlgorithm.ECDH_ES_A128KW;
    }
}
 
Example #26
Source File: JweUtils.java    From cxf with Apache License 2.0 5 votes vote down vote up
public static ContentEncryptionProvider getEcdhDirectContentEncryptionProvider(JsonWebKey key, JweHeaders headers) {
    String curve = key.getStringProperty(JsonWebKey.EC_CURVE);
    if (curve == null) {
        curve = JsonWebKey.EC_CURVE_P256;
    }
    ECPublicKey ecKey = JwkUtils.toECPublicKey(key);
    return new EcdhAesGcmContentEncryptionAlgorithm(ecKey, curve, null, null, 
        headers.getContentEncryptionAlgorithm());
}
 
Example #27
Source File: JwkJoseCookBookTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
private void validatePrivateRsaKey(JsonWebKey key) {
    validatePublicRsaKey(key);
    assertEquals(RSA_PRIVATE_EXP_VALUE, key.getProperty(JsonWebKey.RSA_PRIVATE_EXP));
    assertEquals(RSA_FIRST_PRIME_FACTOR_VALUE, key.getProperty(JsonWebKey.RSA_FIRST_PRIME_FACTOR));
    assertEquals(RSA_SECOND_PRIME_FACTOR_VALUE, key.getProperty(JsonWebKey.RSA_SECOND_PRIME_FACTOR));
    assertEquals(RSA_FIRST_PRIME_CRT_VALUE, key.getProperty(JsonWebKey.RSA_FIRST_PRIME_CRT));
    assertEquals(RSA_SECOND_PRIME_CRT_VALUE, key.getProperty(JsonWebKey.RSA_SECOND_PRIME_CRT));
    assertEquals(RSA_FIRST_CRT_COEFFICIENT_VALUE, key.getProperty(JsonWebKey.RSA_FIRST_CRT_COEFFICIENT));
}
 
Example #28
Source File: ApacheCXFProducer.java    From cxf with Apache License 2.0 5 votes vote down vote up
private void produceJsonJWE(String keyEncryptionAlgorithm, String contentEncryptionAlgorithm, String plainText,
    JsonWebKey key, boolean flattened) {
    JweHeaders protectedHeaders = new JweHeaders();
    protectedHeaders.setKeyEncryptionAlgorithm(KeyAlgorithm.getAlgorithm(keyEncryptionAlgorithm));
    protectedHeaders
        .setContentEncryptionAlgorithm(ContentAlgorithm.getAlgorithm(contentEncryptionAlgorithm));
    JweHeaders recipientHeaders = new JweHeaders(key.getKeyId());
    produceJsonJWE(plainText, key, protectedHeaders, null, recipientHeaders, flattened);
}
 
Example #29
Source File: JweUtils.java    From cxf with Apache License 2.0 5 votes vote down vote up
public static JsonWebKeys loadPublicKeyEncryptionKeys(Message m, Properties props) {
    String storeType = props.getProperty(JoseConstants.RSSEC_KEY_STORE_TYPE);
    if ("jwk".equals(storeType)) {
        return JwkUtils.loadPublicJwkSet(m, props);
    }
    //TODO: consider loading all the public keys in the store
    PublicKey key = KeyManagementUtils.loadPublicKey(m, props);
    JsonWebKey jwk = JwkUtils.fromPublicKey(key, props, JoseConstants.RSSEC_ENCRYPTION_KEY_ALGORITHM);
    return new JsonWebKeys(jwk);
}
 
Example #30
Source File: JwkJoseCookBookTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
private void validatePrivateSet(JsonWebKeys jwks) throws Exception {
    List<JsonWebKey> keys = jwks.getKeys();
    assertEquals(2, keys.size());
    JsonWebKey ecKey = keys.get(0);
    assertEquals(7, ecKey.asMap().size());
    validatePrivateEcKey(ecKey);
    JsonWebKey rsaKey = keys.get(1);
    assertEquals(11, rsaKey.asMap().size());
    validatePrivateRsaKey(rsaKey);
}