org.apache.cxf.rs.security.jose.jwa.SignatureAlgorithm Java Examples

The following examples show how to use org.apache.cxf.rs.security.jose.jwa.SignatureAlgorithm. 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: BigQueryServer.java    From cxf with Apache License 2.0 6 votes vote down vote up
private static ClientAccessToken getAccessToken(PrivateKey privateKey, String issuer) {
    JwsHeaders headers = new JwsHeaders(JoseType.JWT, SignatureAlgorithm.RS256);
    JwtClaims claims = new JwtClaims();
    claims.setIssuer(issuer);
    claims.setAudience("https://www.googleapis.com/oauth2/v3/token");

    long issuedAt = OAuthUtils.getIssuedAt();
    claims.setIssuedAt(issuedAt);
    claims.setExpiryTime(issuedAt + 60 * 60);
    claims.setProperty("scope", "https://www.googleapis.com/auth/bigquery.readonly");

    JwtToken token = new JwtToken(headers, claims);
    JwsJwtCompactProducer p = new JwsJwtCompactProducer(token);
    String base64UrlAssertion = p.signWith(privateKey);

    JwtBearerGrant grant = new JwtBearerGrant(base64UrlAssertion);

    WebClient accessTokenService = WebClient.create("https://www.googleapis.com/oauth2/v3/token",
                                                    Arrays.asList(new OAuthJSONProvider(),
                                                                  new AccessTokenGrantWriter()));
    WebClient.getConfig(accessTokenService).getInInterceptors().add(new LoggingInInterceptor());

    accessTokenService.type(MediaType.APPLICATION_FORM_URLENCODED).accept(MediaType.APPLICATION_JSON);

    return accessTokenService.post(grant, ClientAccessToken.class);
}
 
Example #2
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 #3
Source File: ApacheCXFConsumer.java    From cxf with Apache License 2.0 6 votes vote down vote up
protected void consumeCompactJWS(String signedData, String plainText, JsonWebKeys keys) {

        // Validate Signature

        // 1. Read data to get key id (only need to do this if you don't know the key)
        JwsCompactConsumer jwsConsumer = new JwsCompactConsumer(signedData);
        String kid = jwsConsumer.getJwsHeaders().getKeyId();

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

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

        // 3. Verify
        SignatureAlgorithm signAlgo = jwsConsumer.getJwsHeaders().getSignatureAlgorithm();
        Assert.assertNotNull("Signed data does not define algorithm used", signAlgo);
        JwsSignatureVerifier signatureVerifier = JwsUtils.getSignatureVerifier(key, signAlgo);
        Assert.assertTrue("Signature validation failed", jwsConsumer.verifySignatureWith(signatureVerifier));

        // Validate plain text
        Assert.assertEquals(plainText, jwsConsumer.getDecodedJwsPayload());
    }
 
Example #4
Source File: AbstractITCase.java    From syncope with Apache License 2.0 6 votes vote down vote up
@BeforeAll
public static void securitySetup() {
    try (InputStream propStream = Encryptor.class.getResourceAsStream("/security.properties")) {
        Properties props = new Properties();
        props.load(propStream);

        ANONYMOUS_UNAME = props.getProperty("anonymousUser");
        ANONYMOUS_KEY = props.getProperty("anonymousKey");
        JWT_ISSUER = props.getProperty("jwtIssuer");
        JWS_ALGORITHM = SignatureAlgorithm.valueOf(props.getProperty("jwsAlgorithm"));
        JWS_KEY = props.getProperty("jwsKey");
    } catch (Exception e) {
        LOG.error("Could not read secretKey", e);
    }

    assertNotNull(ANONYMOUS_UNAME);
    assertNotNull(ANONYMOUS_KEY);
    assertNotNull(JWS_KEY);
    assertNotNull(JWT_ISSUER);
}
 
Example #5
Source File: AuthorizationGrantTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
private static void validateAccessToken(String accessToken)
    throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException {
    JwsJwtCompactConsumer jwtConsumer = new JwsJwtCompactConsumer(accessToken);
    JwtClaims jwtClaims = jwtConsumer.getJwtToken().getClaims();

    // Validate claims
    if (!OAuthConstants.CLIENT_CREDENTIALS_GRANT.equals(jwtClaims.getStringProperty(OAuthConstants.GRANT_TYPE))) {
        // We don't have a Subject for the client credential grant
        assertNotNull(jwtClaims.getSubject());
    }
    assertNotNull(jwtClaims.getIssuedAt());
    assertNotNull(jwtClaims.getExpiryTime());
    assertEquals(ISSUER, jwtClaims.getIssuer());

    KeyStore keystore = KeyStore.getInstance("JKS");
    keystore.load(ClassLoaderUtils.getResourceAsStream("keys/alice.jks", AuthorizationGrantTest.class),
                  "password".toCharArray());
    Certificate cert = keystore.getCertificate("alice");
    assertNotNull(cert);

    assertTrue(jwtConsumer.verifySignatureWith((X509Certificate)cert,
                                                      SignatureAlgorithm.RS256));
}
 
Example #6
Source File: OidcUtils.java    From cxf with Apache License 2.0 6 votes vote down vote up
private static String calculateHash(String value, SignatureAlgorithm sigAlgo) {
    if (sigAlgo == SignatureAlgorithm.NONE) {
        throw new JwsException(JwsException.Error.INVALID_ALGORITHM);
    }
    String algoShaSizeString = sigAlgo.getJwaName().substring(2);
    String javaShaAlgo = "SHA-" + algoShaSizeString;
    int algoShaSize = Integer.parseInt(algoShaSizeString);
    int valueHashSize = (algoShaSize / 8) / 2;
    try {
        byte[] atBytes = StringUtils.toBytesASCII(value);
        byte[] digest = MessageDigestUtils.createDigest(atBytes,  javaShaAlgo);
        return Base64UrlUtility.encodeChunk(digest, 0, valueHashSize);
    } catch (NoSuchAlgorithmException ex) {
        throw new OAuthServiceException(ex);
    }
}
 
Example #7
Source File: JwsCompactReaderWriterTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Test
public void testWriteReadJwsUnsigned() throws Exception {
    JwsHeaders headers = new JwsHeaders(JoseType.JWT);
    headers.setSignatureAlgorithm(SignatureAlgorithm.NONE);

    JwtClaims claims = new JwtClaims();
    claims.setIssuer("https://jwt-idp.example.com");
    claims.setSubject("mailto:[email protected]");
    claims.setAudiences(Collections.singletonList("https://jwt-rp.example.net"));
    claims.setNotBefore(1300815780L);
    claims.setExpiryTime(1300819380L);
    claims.setClaim("http://claims.example.com/member", true);

    JwsCompactProducer writer = new JwsJwtCompactProducer(headers, claims);
    String signed = writer.getSignedEncodedJws();

    JwsJwtCompactConsumer reader = new JwsJwtCompactConsumer(signed);
    assertEquals(0, reader.getDecodedSignature().length);

    JwtToken token = reader.getJwtToken();
    assertEquals(new JwtToken(headers, claims), token);
}
 
Example #8
Source File: STSRESTTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
private static JwtToken validateJWTToken(String token)
    throws Exception {
    assertNotNull(token);
    JwsJwtCompactConsumer jwtConsumer = new JwsJwtCompactConsumer(token);
    JwtToken jwt = jwtConsumer.getJwtToken();

    // Validate claims
    assertEquals("DoubleItSTSIssuer", jwt.getClaims().getIssuer());
    assertNotNull(jwt.getClaims().getExpiryTime());
    assertNotNull(jwt.getClaims().getIssuedAt());

    CryptoType alias = new CryptoType(CryptoType.TYPE.ALIAS);
    alias.setAlias("mystskey");
    X509Certificate stsCertificate = serviceCrypto.getX509Certificates(alias)[0];
    assertTrue(jwtConsumer.verifySignatureWith(stsCertificate, SignatureAlgorithm.RS256));

    return jwt;
}
 
Example #9
Source File: OidcImplicitService.java    From cxf with Apache License 2.0 6 votes vote down vote up
protected String processIdToken(OAuthRedirectionState state, IdToken idToken) {
    OAuthJoseJwtProducer processor = idTokenHandler == null ? new OAuthJoseJwtProducer() : idTokenHandler;

    String code =
        (String)JAXRSUtils.getCurrentMessage().getExchange().get(OAuthConstants.AUTHORIZATION_CODE_VALUE);
    if (code != null) {
        // this service is invoked as part of the hybrid flow
        Properties props = JwsUtils.loadSignatureOutProperties(false);
        SignatureAlgorithm sigAlgo = null;
        if (processor.isSignWithClientSecret()) {
            sigAlgo = OAuthUtils.getClientSecretSignatureAlgorithm(props);
        } else {
            sigAlgo = JwsUtils.getSignatureAlgorithm(props, SignatureAlgorithm.RS256);
        }
        idToken.setAuthorizationCodeHash(OidcUtils.calculateAuthorizationCodeHash(code, sigAlgo));
    }

    idToken.setNonce(state.getNonce());
    return processor.processJwt(new JwtToken(idToken));
}
 
Example #10
Source File: JwsCompactReaderWriterTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
private void doTestWriteJwsWithJwkSignedByMac(Object jsonWebKey) throws Exception {
    JwsHeaders headers = new JwsHeaders();
    headers.setType(JoseType.JWT);
    headers.setSignatureAlgorithm(SignatureAlgorithm.HS256);
    headers.setHeader(JoseConstants.HEADER_JSON_WEB_KEY, jsonWebKey);

    JwtClaims claims = new JwtClaims();
    claims.setIssuer("joe");
    claims.setExpiryTime(1300819380L);
    claims.setClaim("http://example.com/is_root", Boolean.TRUE);

    JwtToken token = new JwtToken(headers, claims);
    JwsCompactProducer jws = new JwsJwtCompactProducer(token, getWriter());
    jws.signWith(new HmacJwsSignatureProvider(ENCODED_MAC_KEY, SignatureAlgorithm.HS256));

    assertEquals(ENCODED_TOKEN_WITH_JSON_KEY_SIGNED_BY_MAC, jws.getSignedEncodedJws());
}
 
Example #11
Source File: OIDCFlowTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
private void validateIdToken(String idToken, String nonce)
    throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException {
    JwsJwtCompactConsumer jwtConsumer = new JwsJwtCompactConsumer(idToken);
    JwtToken jwt = jwtConsumer.getJwtToken();

    // Validate claims
    assertEquals("alice", jwt.getClaim(JwtConstants.CLAIM_SUBJECT));
    assertEquals("OIDC IdP", jwt.getClaim(JwtConstants.CLAIM_ISSUER));
    assertEquals("consumer-id", jwt.getClaim(JwtConstants.CLAIM_AUDIENCE));
    assertNotNull(jwt.getClaim(JwtConstants.CLAIM_EXPIRY));
    assertNotNull(jwt.getClaim(JwtConstants.CLAIM_ISSUED_AT));
    if (nonce != null) {
        assertEquals(nonce, jwt.getClaim(IdToken.NONCE_CLAIM));
    }

    KeyStore keystore = KeyStore.getInstance("JKS");
    keystore.load(ClassLoaderUtils.getResourceAsStream("keys/alice.jks", this.getClass()),
                  "password".toCharArray());
    Certificate cert = keystore.getCertificate("alice");
    assertNotNull(cert);

    assertTrue(jwtConsumer.verifySignatureWith((X509Certificate)cert,
                                                      SignatureAlgorithm.RS256));
}
 
Example #12
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 #13
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 #14
Source File: JwsJsonProducerTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testDualSignWithProtectedHeaderOnly() {
    JwsJsonProducer producer = new JwsJsonProducer(UNSIGNED_PLAIN_JSON_DOCUMENT);
    JwsHeaders headerEntries = new JwsHeaders();
    headerEntries.setSignatureAlgorithm(SignatureAlgorithm.HS256);

    producer.signWith(new HmacJwsSignatureProvider(ENCODED_MAC_KEY_1, SignatureAlgorithm.HS256),
                      headerEntries);
    producer.signWith(new HmacJwsSignatureProvider(ENCODED_MAC_KEY_2, SignatureAlgorithm.HS256),
                      headerEntries);
    assertEquals(DUAL_SIGNED_JWS_JSON_DOCUMENT,
                 producer.getJwsJsonSignedDocument());
}
 
Example #15
Source File: JwsUtils.java    From cxf with Apache License 2.0 5 votes vote down vote up
private static SignatureAlgorithm getDefaultPrivateKeyAlgorithm(PrivateKey key) {
    if (key instanceof RSAPrivateKey) {
        return SignatureAlgorithm.RS256;
    } else if (key instanceof ECPrivateKey) {
        return SignatureAlgorithm.ES256;
    } else {
        return null;
    }
}
 
Example #16
Source File: JwsCompactHeaderTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void verifyJwsWithTwoAlgHeaderFieldsBogusFieldLast() throws Exception {
    JwsCompactConsumer jwsConsumer = new JwsCompactConsumer(TWO_ALG_HEADER_FIELDS_IN_JWS_BOGUS_LAST);

    assertFalse(jwsConsumer.verifySignatureWith(new HmacJwsSignatureVerifier(ENCODED_MAC_KEY,
                                                    SignatureAlgorithm.HS256)));
}
 
Example #17
Source File: SecurityContext.java    From syncope with Apache License 2.0 5 votes vote down vote up
@ConditionalOnMissingBean
@Bean
public AccessTokenJwsSignatureVerifier accessTokenJwsSignatureVerifier() {
    AccessTokenJwsSignatureVerifier verifier = new AccessTokenJwsSignatureVerifier();
    verifier.setJwsAlgorithm(env.getProperty("jwsAlgorithm", SignatureAlgorithm.class));
    verifier.setJwsKey(jwsKey());
    return verifier;
}
 
Example #18
Source File: HmacJwsSignatureVerifier.java    From cxf with Apache License 2.0 5 votes vote down vote up
protected String checkAlgorithm(SignatureAlgorithm sigAlgo) {

        if (sigAlgo == null) {
            LOG.warning("Signature algorithm is not set");
            throw new JwsException(JwsException.Error.ALGORITHM_NOT_SET);
        }
        String algo = sigAlgo.getJwaName();
        if (!AlgorithmUtils.isHmacSign(algo)
            || !algo.equals(supportedAlgo.getJwaName())) {
            LOG.warning("Invalid signature algorithm: " + algo);
            throw new JwsException(JwsException.Error.INVALID_ALGORITHM);
        }
        return algo;
    }
 
Example #19
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 #20
Source File: JwsUtils.java    From cxf with Apache License 2.0 5 votes vote down vote up
public static SignatureAlgorithm getSignatureAlgorithm(Message m, Properties props,
                                           SignatureAlgorithm algo,
                                           SignatureAlgorithm defaultAlgo) {
    if (algo == null) {
        algo = getSignatureAlgorithm(m, props, defaultAlgo);
    }
    return algo;
}
 
Example #21
Source File: JwtRequestCodeFilter.java    From cxf with 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 #22
Source File: AbstractOAuthDataProviderTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
protected static void initializeProvider(AbstractOAuthDataProvider dataProvider) {
    dataProvider.setSupportedScopes(Collections.singletonMap("a", "A Scope"));
    dataProvider.setSupportedScopes(Collections.singletonMap("refreshToken", "RefreshToken"));

    // Configure the means of signing the issued JWT tokens
    if (dataProvider.isUseJwtFormatForAccessTokens()) {
        final JwsSignatureProvider signatureProvider =
            new PrivateKeyJwsSignatureProvider(keyPair.getPrivate(), SignatureAlgorithm.RS256);

        OAuthJoseJwtProducer jwtAccessTokenProducer = new OAuthJoseJwtProducer();
        jwtAccessTokenProducer.setSignatureProvider(signatureProvider);
        dataProvider.setJwtAccessTokenProducer(jwtAccessTokenProducer);
    }
}
 
Example #23
Source File: AbstractOAuthDataProviderTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
private void validateAccessToken(ServerAccessToken accessToken) {
    if (getProvider().isUseJwtFormatForAccessTokens()) {
        JwsJwtCompactConsumer jwtConsumer = new JwsJwtCompactConsumer(accessToken.getTokenKey());
        JwtToken jwt = jwtConsumer.getJwtToken();

        // Validate claims
        assertNotNull(jwt.getClaim(JwtConstants.CLAIM_EXPIRY));
        assertNotNull(jwt.getClaim(JwtConstants.CLAIM_ISSUED_AT));

        assertTrue(jwtConsumer.verifySignatureWith(keyPair.getPublic(), SignatureAlgorithm.RS256));
    }
}
 
Example #24
Source File: JwsCompactReaderWriterTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testWriteJwsSignedByPrivateKey() throws Exception {
    JwsHeaders headers = new JwsHeaders();
    headers.setSignatureAlgorithm(SignatureAlgorithm.RS256);
    JwsCompactProducer jws = initSpecJwtTokenWriter(headers);
    PrivateKey key = CryptoUtils.getRSAPrivateKey(RSA_MODULUS_ENCODED, RSA_PRIVATE_EXPONENT_ENCODED);
    jws.signWith(new PrivateKeyJwsSignatureProvider(key, SignatureAlgorithm.RS256));

    assertEquals(ENCODED_TOKEN_SIGNED_BY_PRIVATE_KEY, jws.getSignedEncodedJws());
}
 
Example #25
Source File: JwsUtils.java    From cxf with Apache License 2.0 5 votes vote down vote up
public static SignatureAlgorithm getSignatureAlgorithm(Message m,
                                                       Properties props,
                                                       SignatureAlgorithm defaultAlgo) {
    String algo = KeyManagementUtils.getKeyAlgorithm(m,
                                              props,
                                              JoseConstants.RSSEC_SIGNATURE_ALGORITHM,
                                              defaultAlgo == null ? null : defaultAlgo.getJwaName());
    return SignatureAlgorithm.getAlgorithm(algo);
}
 
Example #26
Source File: JwsCompactReaderWriterTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testReadJwsSignedByMacSpecExample() throws Exception {
    JwsJwtCompactConsumer jws = new JwsJwtCompactConsumer(ENCODED_TOKEN_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());
    validateSpecClaim(token.getClaims());
}
 
Example #27
Source File: JwsUtils.java    From cxf with Apache License 2.0 5 votes vote down vote up
public static JwsSignatureVerifier getPublicKeySignatureVerifier(PublicKey key, SignatureAlgorithm algo) {
    if (algo == null) {
        LOG.warning("No signature algorithm was defined");
        throw new JwsException(JwsException.Error.ALGORITHM_NOT_SET);
    }

    if (key instanceof RSAPublicKey) {
        return new PublicKeyJwsSignatureVerifier(key, algo);
    } else if (key instanceof ECPublicKey) {
        return new EcDsaJwsSignatureVerifier(key, algo);
    }

    return null;
}
 
Example #28
Source File: PublicKeyJwsSignatureVerifier.java    From cxf with Apache License 2.0 5 votes vote down vote up
public PublicKeyJwsSignatureVerifier(X509Certificate cert,
                                     AlgorithmParameterSpec spec,
                                     SignatureAlgorithm supportedAlgo) {
    if (cert != null) {
        this.key = cert.getPublicKey();
    } else {
        this.key = null;
    }
    this.cert = cert;
    this.signatureSpec = spec;
    this.supportedAlgo = supportedAlgo;
    JwsUtils.checkSignatureKeySize(key);
}
 
Example #29
Source File: PublicKeyJwsSignatureVerifier.java    From cxf with Apache License 2.0 5 votes vote down vote up
public PublicKeyJwsSignatureVerifier(PublicKey key, AlgorithmParameterSpec spec, SignatureAlgorithm supportedAlgo) {
    this.key = key;
    cert = null;
    this.signatureSpec = spec;
    this.supportedAlgo = supportedAlgo;
    JwsUtils.checkSignatureKeySize(key);
}
 
Example #30
Source File: JwsJsonProducerTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testSignWithProtectedHeaderOnlyUnencodedPayload() {
    JwsJsonProducer producer = new JwsJsonProducer(UNSIGNED_PLAIN_DOCUMENT, true);
    JwsHeaders headers = new JwsHeaders();
    headers.setSignatureAlgorithm(SignatureAlgorithm.HS256);
    headers.setPayloadEncodingStatus(false);


    producer.signWith(new HmacJwsSignatureProvider(ENCODED_MAC_KEY_1, SignatureAlgorithm.HS256),
                      headers);
    assertEquals(SIGNED_JWS_JSON_FLAT_UNENCODED_DOCUMENT,
                 producer.getJwsJsonSignedDocument());
}