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

The following examples show how to use org.apache.cxf.rt.security.crypto.CryptoUtils. 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: JwkUtilsTest.java    From cxf with 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 #2
Source File: ClientCodeRequestFilter.java    From cxf with 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 #3
Source File: JwsCompactReaderWriterTest.java    From cxf with 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 #4
Source File: AbstractContentEncryptionAlgorithm.java    From cxf with 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 #5
Source File: ModelEncryptionSupport.java    From cxf with 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 File: OAuthServerJoseJwtProducer.java    From cxf with 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 #7
Source File: ModelEncryptionSupport.java    From cxf with 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 #8
Source File: AbstractJweEncryption.java    From cxf with 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 #9
Source File: ModelEncryptionSupport.java    From cxf with 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 #10
Source File: JweJsonConsumerTest.java    From cxf with 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 #11
Source File: JweCompactReaderWriterTest.java    From cxf with 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 #12
Source File: WrappedKeyDecryptionAlgorithm.java    From cxf with 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 #13
Source File: KeyManagementUtils.java    From cxf with 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 #14
Source File: TLSClientParametersUtils.java    From cxf with 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 #15
Source File: CryptoUtilsTest.java    From cxf with 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 #16
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 #17
Source File: JwsCompactReaderWriterTest.java    From cxf with 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 #18
Source File: CryptoUtilsTest.java    From cxf with 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 #19
Source File: JweJsonConsumerTest.java    From cxf with 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 #20
Source File: JweCompactReaderWriterTest.java    From cxf with 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 File: KeyManagementUtils.java    From cxf with Apache License 2.0 5 votes vote down vote up
public static KeyStore loadKeyStore(String keyStoreLoc,
                                    String keyStoreType,
                                    String keyStorePswd,
                                    Bus bus) {
    if (keyStorePswd == null) {
        throw new JoseException("No keystore password was defined");
    }
    try (InputStream is = JoseUtils.getResourceStream(keyStoreLoc, bus)) {
        return CryptoUtils.loadKeyStore(is, keyStorePswd.toCharArray(), keyStoreType);
    } catch (Exception ex) {
        LOG.warning("Key store can not be loaded");
        throw new JoseException(ex);
    }
}
 
Example #22
Source File: JweJsonProducerTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
private String doTestSingleRecipient(String text,
                                     String expectedOutput,
                                     ContentAlgorithm contentEncryptionAlgo,
                                     final byte[] wrapperKeyBytes,
                                     final byte[] iv,
                                     final byte[] cek,
                                     boolean canBeFlat) throws Exception {
    JweHeaders headers = new JweHeaders(KeyAlgorithm.A128KW,
                                        contentEncryptionAlgo);
    JweEncryptionProvider jwe = null;
    if (wrapperKeyBytes == null) {
        headers.asMap().remove("alg");
        SecretKey cekKey = CryptoUtils.createSecretKeySpec(cek, "AES");
        jwe = JweUtils.getDirectKeyJweEncryption(cekKey, contentEncryptionAlgo);
    } else {
        SecretKey wrapperKey = CryptoUtils.createSecretKeySpec(wrapperKeyBytes, "AES");
        jwe = JweUtils.createJweEncryptionProvider(wrapperKey, headers);
    }
    JweJsonProducer p = new JweJsonProducer(headers, StringUtils.toBytesUTF8(text), canBeFlat) {
        protected JweEncryptionInput createEncryptionInput(JweHeaders jsonHeaders) {
            JweEncryptionInput input = super.createEncryptionInput(jsonHeaders);
            input.setCek(cek);
            input.setIv(iv);
            return input;
        }
    };
    String jweJson = p.encryptWith(jwe);
    assertEquals(expectedOutput, jweJson);
    return jweJson;
}
 
Example #23
Source File: KeyManagementUtils.java    From cxf with Apache License 2.0 5 votes vote down vote up
public static PublicKey loadPublicKey(String keyStoreLoc,
                                      String keyStorePassword,
                                      String keyAlias,
                                      Bus bus) {
    try {
        KeyStore keyStore = loadKeyStore(keyStoreLoc, null, keyStorePassword, bus);
        return CryptoUtils.loadPublicKey(keyStore, keyAlias);
    } catch (Exception ex) {
        throw new SecurityException(ex);
    }
}
 
Example #24
Source File: KeyManagementUtils.java    From cxf with Apache License 2.0 5 votes vote down vote up
private static X509Certificate[] loadX509CertificateOrChain(KeyStore keyStore, String alias) {
    if (alias == null) {
        throw new JoseException("No alias supplied");
    }
    try {
        Certificate[] certs = keyStore.getCertificateChain(alias);
        if (certs != null) {
            return Arrays.copyOf(certs, certs.length, X509Certificate[].class);
        }
        return new X509Certificate[]{(X509Certificate)CryptoUtils.loadCertificate(keyStore, alias)};
    } catch (Exception ex) {
        LOG.warning("X509 Certificates can not be created");
        throw new JoseException(ex);
    }
}
 
Example #25
Source File: KeyManagementUtils.java    From cxf with Apache License 2.0 5 votes vote down vote up
public static PrivateKey loadPrivateKey(String keyStoreLoc,
                                        String keyStorePassword,
                                        String keyAlias,
                                        String keyPassword,
                                        Bus bus) {
    try {
        KeyStore keyStore = loadKeyStore(keyStoreLoc, null, keyStorePassword, bus);
        return CryptoUtils.loadPrivateKey(keyStore,
                                          keyPassword == null ? new char[]{} : keyPassword.toCharArray(),
                                          keyAlias);
    } catch (Exception ex) {
        throw new SecurityException(ex);
    }
}
 
Example #26
Source File: JwkUtils.java    From cxf with Apache License 2.0 5 votes vote down vote up
public static RSAPublicKey toRSAPublicKey(JsonWebKey jwk, boolean checkX509) {
    String encodedModulus = (String)jwk.getProperty(JsonWebKey.RSA_MODULUS);
    String encodedPublicExponent = (String)jwk.getProperty(JsonWebKey.RSA_PUBLIC_EXP);
    if (encodedModulus != null) {
        return CryptoUtils.getRSAPublicKey(encodedModulus, encodedPublicExponent);
    } else if (checkX509) {
        List<X509Certificate> chain = toX509CertificateChain(jwk);
        return (RSAPublicKey)chain.get(0).getPublicKey();
    }
    return null;
}
 
Example #27
Source File: KeyManagementUtils.java    From cxf with Apache License 2.0 5 votes vote down vote up
public static PrivateKey loadPrivateKey(Message m, Properties props) {
    KeyStore keyStore = loadPersistKeyStore(m, props);

    String keyPswd = props.getProperty(HTTPSignatureConstants.RSSEC_KEY_PSWD);
    String alias = props.getProperty(HTTPSignatureConstants.RSSEC_KEY_STORE_ALIAS);
    char[] keyPswdChars = keyPswd != null ? keyPswd.toCharArray() : null;
    if (keyPswdChars == null) {
        PrivateKeyPasswordProvider provider = loadPasswordProvider(m, props);
        keyPswdChars = provider != null ? provider.getPassword(props) : null;
    }
    return CryptoUtils.loadPrivateKey(keyStore, keyPswdChars, alias);
}
 
Example #28
Source File: PrivateKeyJwsSignatureProvider.java    From cxf with Apache License 2.0 5 votes vote down vote up
protected JwsSignature doCreateJwsSignature(JwsHeaders headers) {
    final String sigAlgo = headers.getSignatureAlgorithm().getJwaName();
    final Signature s = CryptoUtils.getSignature(key,
                                                 AlgorithmUtils.toJavaName(sigAlgo),
                                                 random,
                                                 signatureSpec);
    return doCreateJwsSignature(s);
}
 
Example #29
Source File: JweJsonConsumerTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testMultipleRecipientsAutogeneratedCek() {
    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");

    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(ContentAlgorithm.A128GCM, true);

    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> perRecipientHeaders = new LinkedList<>();
    perRecipientHeaders.add(new JweHeaders("key1"));
    perRecipientHeaders.add(new JweHeaders("key2"));

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

    String jweJson = p.encryptWith(jweProviders, perRecipientHeaders);
    doTestMultipleRecipients(jweJson);
}
 
Example #30
Source File: JweCompactReaderWriterTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
private SecretKey createSecretKey(boolean createIfException) throws Exception {
    SecretKey key = null;
    if (Cipher.getMaxAllowedKeyLength("AES") > 128) {
        key = CryptoUtils.createSecretKeySpec(CONTENT_ENCRYPTION_KEY_A1, "AES");
    } else if (createIfException) {
        key = CryptoUtils.createSecretKeySpec(CryptoUtils.generateSecureRandomBytes(128 / 8), "AES");
    }
    return key;
}