Java Code Examples for org.apache.cxf.rt.security.crypto.CryptoUtils

The following examples show how to use org.apache.cxf.rt.security.crypto.CryptoUtils. These examples are extracted from open source projects. 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 Project: cxf   Source File: JwsCompactReaderWriterTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testWriteReadJwsSignedByESPrivateKey() throws Exception {
    JwsHeaders headers = new JwsHeaders();
    headers.setSignatureAlgorithm(SignatureAlgorithm.ES256);
    JwsCompactProducer jws = initSpecJwtTokenWriter(headers);
    ECPrivateKey privateKey = CryptoUtils.getECPrivateKey(JsonWebKey.EC_CURVE_P256,
                                                          EC_PRIVATE_KEY_ENCODED);
    jws.signWith(new EcDsaJwsSignatureProvider(privateKey, SignatureAlgorithm.ES256));
    String signedJws = jws.getSignedEncodedJws();

    ECPublicKey publicKey = CryptoUtils.getECPublicKey(JsonWebKey.EC_CURVE_P256,
                                                       EC_X_POINT_ENCODED,
                                                       EC_Y_POINT_ENCODED);
    JwsJwtCompactConsumer jwsConsumer = new JwsJwtCompactConsumer(signedJws);
    assertTrue(jwsConsumer.verifySignatureWith(new EcDsaJwsSignatureVerifier(publicKey,
                                               SignatureAlgorithm.ES256)));
    JwtToken token = jwsConsumer.getJwtToken();
    JwsHeaders headersReceived = new JwsHeaders(token.getJwsHeaders());
    assertEquals(SignatureAlgorithm.ES256, headersReceived.getSignatureAlgorithm());
    validateSpecClaim(token.getClaims());
}
 
Example 2
Source Project: cxf   Source File: TLSClientParametersUtils.java    License: Apache License 2.0 6 votes vote down vote up
public static TLSClientParameters getTLSClientParameters() throws GeneralSecurityException, IOException {
    final TLSClientParameters tlsCP = new TLSClientParameters();
    tlsCP.setDisableCNCheck(true);

    final KeyStore keyStore;
    try (InputStream is = ClassLoaderUtils.getResourceAsStream(CLIENTSTORE, TLSClientParametersUtils.class)) {
        keyStore = CryptoUtils.loadKeyStore(is, KEYSTORE_PASS.toCharArray(), null);
    }

    KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    kmf.init(keyStore, KEY_PASS.toCharArray());
    tlsCP.setKeyManagers(kmf.getKeyManagers());

    TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    tmf.init(keyStore);
    tlsCP.setTrustManagers(tmf.getTrustManagers());

    return tlsCP;
}
 
Example 3
Source Project: cxf   Source File: ModelEncryptionSupport.java    License: Apache License 2.0 6 votes vote down vote up
public static ServerAccessToken decryptAccessToken(OAuthDataProvider provider,
                                             String encodedToken,
                                             String encodedSecretKey,
                                             KeyProperties props) throws SecurityException {
    SecretKey key = CryptoUtils.decodeSecretKey(encodedSecretKey, props.getKeyAlgo());
    ServerAccessToken serverAccessToken = decryptAccessToken(provider, encodedToken, key, props);

    // Clean the secret key from memory when we're done
    try {
        key.destroy();
    } catch (DestroyFailedException ex) {
        // ignore
    }

    return serverAccessToken;
}
 
Example 4
Source Project: cxf   Source File: ModelEncryptionSupport.java    License: Apache License 2.0 6 votes vote down vote up
public static RefreshToken decryptRefreshToken(OAuthDataProvider provider,
                                              String encodedToken,
                                              String encodedSecretKey,
                                              KeyProperties props) throws SecurityException {
    SecretKey key = CryptoUtils.decodeSecretKey(encodedSecretKey, props.getKeyAlgo());
    RefreshToken refreshToken = decryptRefreshToken(provider, encodedToken, key, props);

    // Clean the secret key from memory when we're done
    try {
        key.destroy();
    } catch (DestroyFailedException ex) {
        // ignore
    }

    return refreshToken;
}
 
Example 5
Source Project: cxf   Source File: ModelEncryptionSupport.java    License: Apache License 2.0 6 votes vote down vote up
public static ServerAuthorizationCodeGrant decryptCodeGrant(OAuthDataProvider provider,
                                              String encodedToken,
                                              String encodedSecretKey,
                                              KeyProperties props) throws SecurityException {
    SecretKey key = CryptoUtils.decodeSecretKey(encodedSecretKey, props.getKeyAlgo());
    ServerAuthorizationCodeGrant authzCodeGrant = decryptCodeGrant(provider, encodedToken, key, props);

    // Clean the secret key from memory when we're done
    try {
        key.destroy();
    } catch (DestroyFailedException ex) {
        // ignore
    }

    return authzCodeGrant;
}
 
Example 6
Source Project: cxf   Source File: ClientCodeRequestFilter.java    License: Apache License 2.0 6 votes vote down vote up
protected MultivaluedMap<String, String> createRedirectState(ContainerRequestContext rc,
                                                             UriInfo ui,
                                                             MultivaluedMap<String, String> codeRequestState) {
    if (clientStateManager == null) {
        return new MetadataMap<String, String>();
    }
    String codeVerifier = null;
    if (codeVerifierTransformer != null) {
        codeVerifier = Base64UrlUtility.encode(CryptoUtils.generateSecureRandomBytes(32));
        codeRequestState.putSingle(OAuthConstants.AUTHORIZATION_CODE_VERIFIER,
                                   codeVerifier);
    }
    MultivaluedMap<String, String> redirectState =
        clientStateManager.toRedirectState(mc, codeRequestState);
    if (codeVerifier != null) {
        redirectState.putSingle(OAuthConstants.AUTHORIZATION_CODE_VERIFIER, codeVerifier);
    }
    return redirectState;
}
 
Example 7
Source Project: cxf   Source File: OAuthServerJoseJwtProducer.java    License: Apache License 2.0 6 votes vote down vote up
protected JweEncryptionProvider getInitializedEncryptionProvider(Client c) {
    JweEncryptionProvider theEncryptionProvider = null;
    if (encryptWithClientCertificates && c != null && !c.getApplicationCertificates().isEmpty()) {
        X509Certificate cert =
            (X509Certificate)CryptoUtils.decodeCertificate(c.getApplicationCertificates().get(0));
        theEncryptionProvider = JweUtils.createJweEncryptionProvider(cert.getPublicKey(),
                                                                     KeyAlgorithm.RSA_OAEP,
                                                                     ContentAlgorithm.A128GCM,
                                                                     null);
    }
    if (theEncryptionProvider == null && c != null && c.getClientSecret() != null) {
        theEncryptionProvider = super.getInitializedEncryptionProvider(c.getClientSecret());
    }
    return theEncryptionProvider;

}
 
Example 8
Source Project: cxf   Source File: JweJsonConsumerTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testSingleRecipientAllTypeOfHeadersAndAadModified() {
    SecretKey wrapperKey = CryptoUtils.createSecretKeySpec(JweJsonProducerTest.WRAPPER_BYTES1,
                                                           "AES");
    JweDecryptionProvider jwe = JweUtils.createJweDecryptionProvider(wrapperKey,
                                                                     KeyAlgorithm.A128KW,
                                                                     ContentAlgorithm.A128GCM);
    JweJsonConsumer consumer = new JweJsonConsumer(SINGLE_RECIPIENT_ALL_HEADERS_AAD_MODIFIED_OUTPUT);
    try {
        consumer.decryptWith(jwe);
        fail("AAD check has passed unexpectedly");
    } catch (SecurityException ex) {
        // expected
    }

}
 
Example 9
Source Project: cxf   Source File: CryptoUtilsTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testBearerTokenCertAndSecretKey() throws Exception {
    AccessTokenRegistration atr = prepareTokenRegistration();
    BearerAccessToken token = p.createAccessTokenInternal(atr);

    KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
    KeyPair keyPair = kpg.generateKeyPair();
    PublicKey publicKey = keyPair.getPublic();
    PrivateKey privateKey = keyPair.getPrivate();

    SecretKey secretKey = CryptoUtils.getSecretKey("AES");
    String encryptedSecretKey = CryptoUtils.encryptSecretKey(secretKey, publicKey);

    String encryptedToken = ModelEncryptionSupport.encryptAccessToken(token, secretKey);
    token.setTokenKey(encryptedToken);
    SecretKey decryptedSecretKey = CryptoUtils.decryptSecretKey(encryptedSecretKey, privateKey);
    ServerAccessToken token2 = ModelEncryptionSupport.decryptAccessToken(p, encryptedToken, decryptedSecretKey);
    // compare tokens
    compareAccessTokens(token, token2);
}
 
Example 10
Source Project: cxf   Source File: CryptoUtilsTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testClientJSON() throws Exception {
    Client c = new Client("client", "secret", true);
    c.setSubject(new UserSubject("subject", "id"));
    JSONProvider<Client> jsonp = new JSONProvider<>();
    jsonp.setMarshallAsJaxbElement(true);
    jsonp.setUnmarshallAsJaxbElement(true);
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    jsonp.writeTo(c, Client.class, new Annotation[]{}, MediaType.APPLICATION_JSON_TYPE,
                  new MetadataMap<String, Object>(), bos);
    String encrypted = CryptoUtils.encryptSequence(bos.toString(), p.key);
    String decrypted = CryptoUtils.decryptSequence(encrypted, p.key);
    Client c2 = jsonp.readFrom(Client.class, Client.class,
                                              new Annotation[]{}, MediaType.APPLICATION_JSON_TYPE,
                                              new MetadataMap<String, String>(),
                                              new ByteArrayInputStream(decrypted.getBytes()));

    assertEquals(c.getClientId(), c2.getClientId());
    assertEquals(c.getClientSecret(), c2.getClientSecret());
    assertTrue(c2.isConfidential());
    assertEquals("subject", c2.getSubject().getLogin());
    assertEquals("id", c2.getSubject().getId());
}
 
Example 11
Source Project: cxf   Source File: JweCompactReaderWriterTest.java    License: 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 12
Source Project: cxf   Source File: JweCompactReaderWriterTest.java    License: Apache License 2.0 6 votes vote down vote up
private String encryptContent(String content, boolean createIfException) throws Exception {
    RSAPublicKey publicKey = CryptoUtils.getRSAPublicKey(RSA_MODULUS_ENCODED_A1,
                                                         RSA_PUBLIC_EXPONENT_ENCODED_A1);
    SecretKey key = createSecretKey(createIfException);
    String jwtKeyName = null;
    if (key == null) {
        // the encryptor will generate it
        jwtKeyName = ContentAlgorithm.A128GCM.getJwaName();
    } else {
        jwtKeyName = AlgorithmUtils.toJwaName(key.getAlgorithm(), key.getEncoded().length * 8);
    }
    KeyEncryptionProvider keyEncryptionAlgo = new RSAKeyEncryptionAlgorithm(publicKey,
                                                                             KeyAlgorithm.RSA_OAEP);
    ContentEncryptionProvider contentEncryptionAlgo =
        new AesGcmContentEncryptionAlgorithm(key == null ? null : key.getEncoded(), INIT_VECTOR_A1,
            ContentAlgorithm.getAlgorithm(jwtKeyName));
    JweEncryptionProvider encryptor = new JweEncryption(keyEncryptionAlgo, contentEncryptionAlgo);
    return encryptor.encrypt(content.getBytes(StandardCharsets.UTF_8), null);
}
 
Example 13
Source Project: cxf   Source File: JwsCompactReaderWriterTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testJwsPsSha() throws Exception {
    Security.addProvider(new BouncyCastleProvider());
    try {
        JwsHeaders outHeaders = new JwsHeaders();
        outHeaders.setSignatureAlgorithm(SignatureAlgorithm.PS256);
        JwsCompactProducer producer = initSpecJwtTokenWriter(outHeaders);
        PrivateKey privateKey = CryptoUtils.getRSAPrivateKey(RSA_MODULUS_ENCODED, RSA_PRIVATE_EXPONENT_ENCODED);
        String signed = producer.signWith(
            new PrivateKeyJwsSignatureProvider(privateKey, SignatureAlgorithm.PS256));

        JwsJwtCompactConsumer jws = new JwsJwtCompactConsumer(signed);
        RSAPublicKey key = CryptoUtils.getRSAPublicKey(RSA_MODULUS_ENCODED, RSA_PUBLIC_EXPONENT_ENCODED);
        assertTrue(jws.verifySignatureWith(new PublicKeyJwsSignatureVerifier(key, SignatureAlgorithm.PS256)));
        JwtToken token = jws.getJwtToken();
        JwsHeaders inHeaders = new JwsHeaders(token.getJwsHeaders());
        assertEquals(SignatureAlgorithm.PS256,
                     inHeaders.getSignatureAlgorithm());
        validateSpecClaim(token.getClaims());
    } finally {
        Security.removeProvider(BouncyCastleProvider.PROVIDER_NAME);
    }
}
 
Example 14
Source Project: cxf   Source File: AbstractContentEncryptionAlgorithm.java    License: Apache License 2.0 6 votes vote down vote up
public byte[] getContentEncryptionKey(JweHeaders headers) {
    byte[] theCek = null;
    if (cek == null) {
        String algoJava = getAlgorithm().getJavaName();
        SecretKey secretKey = CryptoUtils.getSecretKey(AlgorithmUtils.stripAlgoProperties(algoJava),
                      getContentEncryptionKeySize(headers));
        theCek = secretKey.getEncoded();
        if (generateCekOnce) {
            synchronized (this) {
                cek = theCek;
            }
        }
        // Clean the key after we're done with it
        try {
            secretKey.destroy();
        } catch (DestroyFailedException e) {
            // ignore
        }
    } else {
        theCek = cek;
    }
    return theCek;
}
 
Example 15
Source Project: cxf   Source File: AbstractJweEncryption.java    License: Apache License 2.0 6 votes vote down vote up
protected byte[] encryptInternal(JweEncryptionInternal state, byte[] content) {
    try {
        SecretKey createCekSecretKey = createCekSecretKey(state);
        byte[] encryptedBytes = CryptoUtils.encryptBytes(content, createCekSecretKey, state.keyProps);

        // Here we're finished with the SecretKey we created, so we can destroy it
        try {
            createCekSecretKey.destroy();
        } catch (DestroyFailedException e) {
            // ignore
        }
        return encryptedBytes;
    } catch (SecurityException ex) {
        LOG.fine(ex.getMessage());
        if (ex.getCause() instanceof NoSuchAlgorithmException) {
            LOG.warning("Unsupported algorithm: " + state.keyProps.getKeyAlgo());
            throw new JweException(JweException.Error.INVALID_CONTENT_ALGORITHM);
        }
        throw new JweException(JweException.Error.CONTENT_ENCRYPTION_FAILURE, ex);
    }
}
 
Example 16
Source Project: cxf   Source File: WrappedKeyDecryptionAlgorithm.java    License: Apache License 2.0 6 votes vote down vote up
public byte[] getDecryptedContentEncryptionKey(JweDecryptionInput jweDecryptionInput) {
    KeyProperties keyProps = new KeyProperties(getKeyEncryptionAlgorithm(jweDecryptionInput));
    AlgorithmParameterSpec spec = getAlgorithmParameterSpec(jweDecryptionInput);
    if (spec != null) {
        keyProps.setAlgoSpec(spec);
    }
    if (!unwrap) {
        keyProps.setBlockSize(getKeyCipherBlockSize());
        return CryptoUtils.decryptBytes(getEncryptedContentEncryptionKey(jweDecryptionInput),
                                        getCekDecryptionKey(), keyProps);
    }
    return CryptoUtils.unwrapSecretKey(getEncryptedContentEncryptionKey(jweDecryptionInput),
                                       getContentEncryptionAlgorithm(jweDecryptionInput),
                                       getCekDecryptionKey(),
                                       keyProps).getEncoded();
}
 
Example 17
Source Project: cxf   Source File: KeyManagementUtils.java    License: Apache License 2.0 6 votes vote down vote up
private static PrivateKey loadPrivateKey(KeyStore keyStore,
                                        Message m,
                                        Properties props,
                                        KeyOperation keyOper,
                                        String alias) {

    String keyPswd = props.getProperty(JoseConstants.RSSEC_KEY_PSWD);
    String theAlias = alias != null ? alias : getKeyId(m, props, JoseConstants.RSSEC_KEY_STORE_ALIAS, keyOper);
    if (theAlias != null) {
        props.put(JoseConstants.RSSEC_KEY_STORE_ALIAS, theAlias);
    }
    char[] keyPswdChars = keyPswd != null ? keyPswd.toCharArray() : null;
    if (keyPswdChars == null) {
        PrivateKeyPasswordProvider provider = loadPasswordProvider(m, props, keyOper);
        keyPswdChars = provider != null ? provider.getPassword(props) : null;
    }
    return CryptoUtils.loadPrivateKey(keyStore, keyPswdChars, theAlias);
}
 
Example 18
Source Project: cxf   Source File: JweJsonConsumerTest.java    License: Apache License 2.0 6 votes vote down vote up
private void doTestMultipleRecipients(String jweJson) {
    final String text = "The true sign of intelligence is not knowledge but imagination.";

    SecretKey wrapperKey1 = CryptoUtils.createSecretKeySpec(JweJsonProducerTest.WRAPPER_BYTES1,
                                                           "AES");
    SecretKey wrapperKey2 = CryptoUtils.createSecretKeySpec(JweJsonProducerTest.WRAPPER_BYTES2,
        "AES");
    JweJsonConsumer consumer = new JweJsonConsumer(jweJson);
    KeyAlgorithm keyAlgo = consumer.getSharedUnprotectedHeader().getKeyEncryptionAlgorithm();
    ContentAlgorithm ctAlgo = consumer.getProtectedHeader().getContentEncryptionAlgorithm();
    // Recipient 1
    JweDecryptionProvider jwe1 = JweUtils.createJweDecryptionProvider(wrapperKey1, keyAlgo, ctAlgo);
    JweDecryptionOutput out1 = consumer.decryptWith(jwe1,
                                                    Collections.singletonMap("kid", "key1"));
    assertEquals(text, out1.getContentText());
    // Recipient 2
    JweDecryptionProvider jwe2 = JweUtils.createJweDecryptionProvider(wrapperKey2, keyAlgo, ctAlgo);

    JweDecryptionOutput out2 = consumer.decryptWith(jwe2,
                                                    Collections.singletonMap("kid", "key2"));
    assertEquals(text, out2.getContentText());

    // Extra AAD
    assertEquals(JweJsonProducerTest.EXTRA_AAD_SOURCE, consumer.getAadText());
}
 
Example 19
Source Project: cxf   Source File: JwkUtilsTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testFromToPublicRsaKey2() throws Exception {
    BigInteger n = new BigInteger(
        "525569531153621228164069013206963023039121751335221395180741421479892725873020691336158448746650762107595"
        + "8352148531548486906896903886764928450353366890712125983926472500064566992690642117517954169974907061547"
        + "3353190040609042090075291281955112293781438730376121249764205272939686534594208819023639183157456093565"
        + "4148815673814517535941780340023556224072529306118783149589148262622268860151306096159642808944513667279"
        + "4704664637866917427597486905443676772669967766269923280637049233876979061993814679654208850149406432368"
        + "2161337544093644200063709176660451323844399667162451308704624790051211834667782115390754507376506824717"
        + "9938484919159962066058375588059543574624283546151162925649987580839763809787286157381728046746195701379"
        + "0902293850442561995774628930418082115864728330723111110174368232384797709242627319756376556142528218939"
        + "7783875183123336240582938265783686836202210705597100765098627429017295706176890505466946207401105614189"
        + "2784165813507235148683348014201150784998715061575093867666453332433607035581378251824779499939486011300"
        + "7245546797308586043310145338620953330797301627631794650975659295961069452157705404946866414340860434286"
        + "65874725802069389719375237126155948350679342167596471110676954951640992376889874630989205394080379", 
        10);
    BigInteger e = new BigInteger("65537", 10);
    RSAPublicKey publicKey = CryptoUtils.getRSAPublicKey(n, e);
    
    JsonWebKey jwk1 = JwkUtils.fromRSAPublicKey(publicKey, KeyAlgorithm.RSA_OAEP_256.getJwaName());
    assertNotNull(jwk1.getProperty(JsonWebKey.RSA_PUBLIC_EXP));
    assertNull(jwk1.getProperty(JsonWebKey.RSA_PRIVATE_EXP));
    RSAPublicKey privateKey2 = JwkUtils.toRSAPublicKey(jwk1);
    assertEquals(privateKey2, publicKey);

}
 
Example 20
Source Project: cxf   Source File: JweCompactReaderWriterTest.java    License: Apache License 2.0 5 votes vote down vote up
private void decrypt(String jweContent, String plainContent, boolean unwrap) throws Exception {
    RSAPrivateKey privateKey = CryptoUtils.getRSAPrivateKey(RSA_MODULUS_ENCODED_A1,
                                                            RSA_PRIVATE_EXPONENT_ENCODED_A1);
    ContentAlgorithm algo = Cipher.getMaxAllowedKeyLength("AES") > 128
        ? ContentAlgorithm.A256GCM : ContentAlgorithm.A128GCM;
    JweDecryptionProvider decryptor = new JweDecryption(new RSAKeyDecryptionAlgorithm(privateKey),
                                          new AesGcmContentDecryptionAlgorithm(algo));
    String decryptedText = decryptor.decrypt(jweContent).getContentText();
    assertEquals(decryptedText, plainContent);
}
 
Example 21
Source Project: cxf   Source File: PublicClientTest.java    License: Apache License 2.0 5 votes vote down vote up
private void testPKCE(CodeVerifierTransformer transformer, String tokenServiceAddress) {
    URL busFile = PublicClientTest.class.getResource("publicclient.xml");

    String address = "https://localhost:" + JCACHE_PORT + "/services/";
    WebClient client = WebClient.create(address, OAuth2TestUtils.setupProviders(),
                                        "alice", "security", busFile.toString());
    // Save the Cookie for the second request...
    WebClient.getConfig(client).getRequestContext().put(
        org.apache.cxf.message.Message.MAINTAIN_SESSION, Boolean.TRUE);

    // Get Authorization Code
    AuthorizationCodeParameters parameters = new AuthorizationCodeParameters();
    parameters.setConsumerId("consumer-id");
    String codeVerifier = Base64UrlUtility.encode(CryptoUtils.generateSecureRandomBytes(32));
    parameters.setCodeChallenge(transformer.transformCodeVerifier(codeVerifier));
    parameters.setCodeChallengeMethod(transformer.getChallengeMethod());
    parameters.setResponseType(OAuthConstants.CODE_RESPONSE_TYPE);
    parameters.setPath("authorize/");

    String location = OAuth2TestUtils.getLocation(client, parameters);
    String code = OAuth2TestUtils.getSubstring(location, "code");
    assertNotNull(code);

    // Now get the access token
    client = WebClient.create(tokenServiceAddress, busFile.toString());
    ClientAccessToken accessToken =
        OAuth2TestUtils.getAccessTokenWithAuthorizationCode(client, code, "consumer-id", null, codeVerifier);
    assertNotNull(accessToken.getTokenKey());
}
 
Example 22
Source Project: cxf   Source File: PublicClientTest.java    License: Apache License 2.0 5 votes vote down vote up
private void testPKCEMissingVerifier(CodeVerifierTransformer transformer, String tokenServiceAddress) {
    URL busFile = PublicClientTest.class.getResource("publicclient.xml");

    String address = "https://localhost:" + JCACHE_PORT + "/services/";
    WebClient client = WebClient.create(address, OAuth2TestUtils.setupProviders(),
                                        "alice", "security", busFile.toString());
    // Save the Cookie for the second request...
    WebClient.getConfig(client).getRequestContext().put(
        org.apache.cxf.message.Message.MAINTAIN_SESSION, Boolean.TRUE);

    // Get Authorization Code
    AuthorizationCodeParameters parameters = new AuthorizationCodeParameters();
    parameters.setConsumerId("consumer-id");
    String codeVerifier = Base64UrlUtility.encode(CryptoUtils.generateSecureRandomBytes(32));
    parameters.setCodeChallenge(transformer.transformCodeVerifier(codeVerifier));
    parameters.setCodeChallengeMethod(transformer.getChallengeMethod());
    parameters.setResponseType(OAuthConstants.CODE_RESPONSE_TYPE);
    parameters.setPath("authorize/");

    String location = OAuth2TestUtils.getLocation(client, parameters);
    String code = OAuth2TestUtils.getSubstring(location, "code");
    assertNotNull(code);

    // Now get the access token
    client = WebClient.create(tokenServiceAddress, busFile.toString());
    try {
        OAuth2TestUtils.getAccessTokenWithAuthorizationCode(client, code, "consumer-id", null);
        fail("Failure expected on a missing verifier");
    } catch (OAuthServiceException ex) {
        assertFalse(ex.getError().getError().isEmpty());
    }
}
 
Example 23
Source Project: cxf   Source File: JwtRequestCodeFilter.java    License: Apache License 2.0 5 votes vote down vote up
protected JwsSignatureVerifier getInitializedSigVerifier(Client c) {
    if (verifyWithClientCertificates) {
        X509Certificate cert =
            (X509Certificate)CryptoUtils.decodeCertificate(c.getApplicationCertificates().get(0));
        return JwsUtils.getPublicKeySignatureVerifier(cert, SignatureAlgorithm.RS256);
    }
    return super.getInitializedSignatureVerifier(c.getClientSecret());
}
 
Example 24
Source Project: cxf   Source File: JwsCompactReaderWriterTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testReadJwsSignedByPrivateKey() throws Exception {
    JwsJwtCompactConsumer jws = new JwsJwtCompactConsumer(ENCODED_TOKEN_SIGNED_BY_PRIVATE_KEY);
    RSAPublicKey key = CryptoUtils.getRSAPublicKey(RSA_MODULUS_ENCODED, RSA_PUBLIC_EXPONENT_ENCODED);
    assertTrue(jws.verifySignatureWith(new PublicKeyJwsSignatureVerifier(key, SignatureAlgorithm.RS256)));
    JwtToken token = jws.getJwtToken();
    JwsHeaders headers = new JwsHeaders(token.getJwsHeaders());
    assertEquals(SignatureAlgorithm.RS256, headers.getSignatureAlgorithm());
    validateSpecClaim(token.getClaims());
}
 
Example 25
Source Project: cxf   Source File: ModelEncryptionSupport.java    License: Apache License 2.0 5 votes vote down vote up
public static Client decryptClient(String encodedSequence, String encodedSecretKey,
                                   KeyProperties props) throws SecurityException {
    SecretKey key = CryptoUtils.decodeSecretKey(encodedSecretKey, props.getKeyAlgo());
    Client client = decryptClient(encodedSequence, key, props);

    // Clean the secret key from memory when we're done
    try {
        key.destroy();
    } catch (DestroyFailedException ex) {
        // ignore
    }

    return client;
}
 
Example 26
Source Project: cxf   Source File: ModelEncryptionSupport.java    License: Apache License 2.0 5 votes vote down vote up
public static ServerAccessToken decryptAccessToken(OAuthDataProvider provider,
                                             String encodedData,
                                             Key secretKey,
                                             KeyProperties props) throws SecurityException {
    String decryptedSequence = CryptoUtils.decryptSequence(encodedData, secretKey, props);
    return recreateAccessToken(provider, encodedData, decryptedSequence);
}
 
Example 27
Source Project: cxf   Source File: ModelEncryptionSupport.java    License: Apache License 2.0 5 votes vote down vote up
public static RefreshToken decryptRefreshToken(OAuthDataProvider provider,
                                               String encodedData,
                                               Key key,
                                               KeyProperties props) throws SecurityException {
    String decryptedSequence = CryptoUtils.decryptSequence(encodedData, key, props);
    return recreateRefreshToken(provider, encodedData, decryptedSequence);
}
 
Example 28
Source Project: cxf   Source File: ModelEncryptionSupport.java    License: Apache License 2.0 5 votes vote down vote up
public static ServerAuthorizationCodeGrant decryptCodeGrant(OAuthDataProvider provider,
                                               String encodedData,
                                               Key key,
                                               KeyProperties props) throws SecurityException {
    String decryptedSequence = CryptoUtils.decryptSequence(encodedData, key, props);
    return recreateCodeGrant(provider, decryptedSequence);
}
 
Example 29
Source Project: cxf   Source File: JweJsonProducerTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testMultipleRecipientsA128GCM() {
    final String text = "The true sign of intelligence is not knowledge but imagination.";
    SecretKey wrapperKey1 = CryptoUtils.createSecretKeySpec(WRAPPER_BYTES1, "AES");
    SecretKey wrapperKey2 = CryptoUtils.createSecretKeySpec(WRAPPER_BYTES2, "AES");

    JweHeaders protectedHeaders = new JweHeaders(ContentAlgorithm.A128GCM);
    JweHeaders sharedUnprotectedHeaders = new JweHeaders();
    sharedUnprotectedHeaders.setJsonWebKeysUrl("https://server.example.com/keys.jwks");
    sharedUnprotectedHeaders.setKeyEncryptionAlgorithm(KeyAlgorithm.A128KW);

    List<JweEncryptionProvider> jweProviders = new LinkedList<>();

    KeyEncryptionProvider keyEncryption1 =
        JweUtils.getSecretKeyEncryptionAlgorithm(wrapperKey1, KeyAlgorithm.A128KW);
    ContentEncryptionProvider contentEncryption =
        new AesGcmContentEncryptionAlgorithm(CEK_BYTES, JweCompactReaderWriterTest.INIT_VECTOR_A1,
                                             ContentAlgorithm.A128GCM);

    JweEncryptionProvider jwe1 = new JweEncryption(keyEncryption1, contentEncryption);
    KeyEncryptionProvider keyEncryption2 =
        JweUtils.getSecretKeyEncryptionAlgorithm(wrapperKey2, KeyAlgorithm.A128KW);
    JweEncryptionProvider jwe2 = new JweEncryption(keyEncryption2, contentEncryption);
    jweProviders.add(jwe1);
    jweProviders.add(jwe2);

    List<JweHeaders> perRecipientHeades = new LinkedList<>();
    perRecipientHeades.add(new JweHeaders("key1"));
    perRecipientHeades.add(new JweHeaders("key2"));

    JweJsonProducer p = new JweJsonProducer(protectedHeaders,
                                            sharedUnprotectedHeaders,
                                            StringUtils.toBytesUTF8(text),
                                            StringUtils.toBytesUTF8(EXTRA_AAD_SOURCE),
                                            false);

    String jweJson = p.encryptWith(jweProviders, perRecipientHeades);
    assertEquals(MULTIPLE_RECIPIENTS_OUTPUT, jweJson);
}
 
Example 30
Source Project: cxf   Source File: JwaSpecTestCasesTest.java    License: Apache License 2.0 5 votes vote down vote up
private void doTestSingleRecipient(String text,
                                     String expectedOutput,
                                     ContentAlgorithm contentEncryptionAlgo,
                                     final byte[] iv,
                                     final byte[] cek) throws Exception {
    JweHeaders headers = new JweHeaders(KeyAlgorithm.A128KW, contentEncryptionAlgo);

    headers.asMap().remove("alg");
    JweEncryptionProvider jwe = null;
    SecretKey cekKey = CryptoUtils.createSecretKeySpec(cek, "AES");
    jwe = JweUtils.getDirectKeyJweEncryption(cekKey, contentEncryptionAlgo);
    JweJsonProducer p = new JweJsonProducer(headers, Hex.decode(text.getBytes())) {
        protected JweEncryptionInput createEncryptionInput(JweHeaders jsonHeaders) {
            JweEncryptionInput input = super.createEncryptionInput(jsonHeaders);
            input.setCek(cek);
            input.setIv(iv);
            return input;
        }
    };
    String jweJson = p.encryptWith(jwe);

    JsonMapObjectReaderWriter jsonReader = new JsonMapObjectReaderWriter();
    Map<String, Object> json = jsonReader.fromJson(jweJson);

    // Check IV matches
    byte[] outputIv = Base64UrlUtility.decode((String)json.get("iv"));
    assertArrayEquals(outputIv, iv);

    // Check CipherText matches
    byte[] cipherTextBytes = Base64UrlUtility.decode((String)json.get("ciphertext"));
    assertArrayEquals(cipherTextBytes, Hex.decode(expectedOutput));
}