org.jose4j.jwk.JsonWebKey Java Examples

The following examples show how to use org.jose4j.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: KeyLocationResolver.java    From smallrye-jwt with Apache License 2.0 6 votes vote down vote up
static PublicKey getKeyFromJsonWebKeys(String kid, List<JsonWebKey> keys, SignatureAlgorithm algo) {
    if (kid != null) {
        for (JsonWebKey currentJwk : keys) {
            if (kid.equals(currentJwk.getKeyId())
                    && (currentJwk.getAlgorithm() == null || algo.getAlgorithm().equals(currentJwk.getAlgorithm()))) {
                return PublicJsonWebKey.class.cast(currentJwk).getPublicKey();
            }
        }
    }
    // if JWK set contains a single JWK only then try to use it
    // but only if 'kid' is not set in both the token and this JWK
    if (keys.size() == 1 && (kid == null || keys.get(0).getKeyId() == null)
            && (keys.get(0).getAlgorithm() == null || algo.getAlgorithm().equals(keys.get(0).getAlgorithm()))) {
        return PublicJsonWebKey.class.cast(keys.get(0)).getPublicKey();
    }
    return null;
}
 
Example #2
Source File: JwtConsumerTest.java    From Jose4j with Apache License 2.0 6 votes vote down vote up
@Test
public void encOnlyWithIntegrityIssues() throws Exception
{
    String jwt = "eyJhbGciOiJkaXIiLCJlbmMiOiJBMTI4Q0JDLUhTMjU2In0..zWNzKpA-QA0BboVl02nz-A.oSy4V6cQ6EnuIMyazDCqc9jEZMC7k8LwLKkrC12Pf-wpFRyDtQjGdIZ_Ndq9JMAnrCbx0bgFSxjKISbXbcnHiA.QsGX3JhHP1Pwy4zQ8Ha9FQ";
    JsonWebKey jsonWebKey = JsonWebKey.Factory.newJwk("{\"kty\":\"oct\",\"k\":\"30WEMkbhwHPBkg_fIfm_4GuzIz5pPZB7_BSfI3dHbbQ\"}");
    DecryptionKeyResolver decryptionKeyResolver = new JwksDecryptionKeyResolver(Collections.singletonList(jsonWebKey));
    JwtConsumer consumer = new JwtConsumerBuilder()
            .setDecryptionKeyResolver(decryptionKeyResolver)
            .setEvaluationTime(NumericDate.fromSeconds(1420230888))
            .setExpectedAudience("me")
            .setExpectedIssuer("me")
            .setRequireExpirationTime()
            .setDisableRequireSignature()
            .build();

    JwtClaims jwtClaims = consumer.processToClaims(jwt);
    Assert.assertThat("value", equalTo(jwtClaims.getStringClaimValue("name")));

    // change some things and make sure it fails
    jwt = "eyJhbGciOiJkaXIiLCJlbmMiOiJBMTI4Q0JDLUhTMjU2In0..zWNzKpA-QA0BboVl02nz-A.eyJpc3MiOiJtZSIsImF1ZCI6Im1lIiwiZXhwIjoxNDIwMjMxNjA2LCJuYW1lIjoidmFsdWUifQ.QsGX3JhHP1Pwy4zQ8Ha9FQ";
    SimpleJwtConsumerTestHelp.expectProcessingFailure(jwt, consumer);

    jwt = "eyJhbGciOiJkaXIiLCJlbmMiOiJBMTI4Q0JDLUhTMjU2In0..zWNzKpA-QA0BboVl02nz-A.u1D7JCpDFeRl69G1L-h3IRrmcOXiWLnhr23ugO2kkDqKVNcO1YQ4Xvl9Sag4aYOnkqUbqe6Wdz8KK3d9q178tA.QsGX3JhHP1Pwy4zQ8Ha9FQ";
    SimpleJwtConsumerTestHelp.expectProcessingFailure(jwt, consumer);
}
 
Example #3
Source File: JwtConsumerTest.java    From Jose4j with Apache License 2.0 6 votes vote down vote up
@Test (expected = InvalidJwtSignatureException.class)
public void jwtBadSig() throws Exception
{
    String jwt = "eyJ0eXAiOiJKV1QiLA0KICJhbGciOiJIUzI1NiJ9." +
            "eyJpc3MiOiJqb2UiLAogImV4cCI6MTkwMDgxOTM4MCwKICJodHRwOi8vZXhhbXBsZS5jb20vaXNfcm9vdCI6dHJ1ZX0." +
            "dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk";
    String jwk = "{\"kty\":\"oct\",\"k\":\"AyM1SysPpbyDfgZld3umj1qzKObwVMkoqQ-EstJQLr_T-1qS0gZH75aKtMN3Yj0iPS4hcgUuTwjAzZr1Z9CAow\"}";

    JwtConsumer consumer = new JwtConsumerBuilder()
            .setVerificationKey(JsonWebKey.Factory.newJwk(jwk).getKey())
            .setEvaluationTime(NumericDate.fromSeconds(1900000380))
            .setExpectedIssuer("joe")
            .setRequireExpirationTime()
            .build();
    consumer.process(jwt);
}
 
Example #4
Source File: AbstractJWKSTest.java    From microprofile-jwt-auth with Apache License 2.0 6 votes vote down vote up
/**
 * Loads the signer-keypair.jwk resource that was generated using https://mkjwk.org
 * and returns the private key
 *
 * @return the private key from the key pair
 */
static PrivateKey loadPrivateKey() throws Exception {
    String jwk = TokenUtils.readResource("/signer-keypair.jwk");
    RsaJsonWebKey rsaJsonWebKey = (RsaJsonWebKey) JsonWebKey.Factory.newJwk(jwk);
    RSAPublicKey pk = rsaJsonWebKey.getRsaPublicKey();
    String e = new String(Base64.getUrlEncoder().withoutPadding().encode(pk.getPublicExponent().toByteArray()));
    byte[] nbytes = pk.getModulus().toByteArray();
    if(nbytes[0] == 0 && nbytes.length > 1) {
        byte[] tmp = new byte[nbytes.length-1];
        System.arraycopy(nbytes, 1, tmp, 0, tmp.length);
        nbytes = tmp;
    }
    String n = new String(Base64.getUrlEncoder().withoutPadding().encode(nbytes));
    System.out.printf("e: %s\n", e);
    System.out.printf("n: %s\n", n);
    n = BigEndianBigInteger.toBase64Url(pk.getModulus());
    System.out.printf("n: %s\n", n);
    return rsaJsonWebKey.getRsaPrivateKey();
}
 
Example #5
Source File: ZipTest.java    From Jose4j with Apache License 2.0 6 votes vote down vote up
public void testJwBadZipValueConsume() throws JoseException
{
    String cs = "eyJ6aXAiOiJiYWQiLCJhbGciOiJkaXIiLCJlbmMiOiJBMTI4Q0JDLUhTMjU2In0.." +
            "ZZZ0nR5f80ikJtaPot4RpQ." +
            "BlDAYKzn9oLH1fhZcR60ZKye7UHslg7s0h7s1ecNZ5A1Df1pq2pBWUwdRKjJRxJAEFbDFoXTFYjV-cLCCE2Uxw." +
            "zasDvsZ3U4YkTDgIUchjiA";

    JsonWebKey jsonWebKey = JsonWebKey.Factory.newJwk("{\"kty\":\"oct\",\"k\":\"q1qm8z2sLFt_CPqwpLuGm-fX6ZKQKnukPHpoJOeykCw\"}");

    JsonWebEncryption jwe = new JsonWebEncryption();
    jwe.setKey(jsonWebKey.getKey());
    jwe.setCompactSerialization(cs);

    try
    {
        String plaintextString = jwe.getPlaintextString();
        fail("Should fail with invalid zip header value but gave: " + plaintextString);
    }
    catch (InvalidAlgorithmException e)
    {
        // just see if the exception message says something about the header name
        assertTrue(e.getMessage().contains(HeaderParameterNames.ZIP));
    }

}
 
Example #6
Source File: KeyLocationResolverTest.java    From smallrye-jwt with Apache License 2.0 6 votes vote down vote up
@Test
public void testLoadHttpsJwksMathchingKid() throws Exception {
    JWTAuthContextInfo contextInfo = new JWTAuthContextInfo("https://github.com/my_key.jwks", "issuer");
    contextInfo.setJwksRefreshInterval(10);

    KeyLocationResolver keyLocationResolver = new KeyLocationResolver(contextInfo) {
        protected HttpsJwks initializeHttpsJwks() {
            return httpsJwks;
        }
    };
    RsaJsonWebKey jwk = new RsaJsonWebKey(key);
    jwk.setKeyId("1");
    when(httpsJwks.getJsonWebKeys()).thenReturn(Collections.singletonList(jwk));
    keyLocationResolver = Mockito.spy(keyLocationResolver);
    when(signature.getHeaders()).thenReturn(headers);
    when(headers.getStringHeaderValue(JsonWebKey.KEY_ID_PARAMETER)).thenReturn("1");

    assertEquals(key, keyLocationResolver.resolveKey(signature, emptyList()));
    assertNull(keyLocationResolver.verificationKey);
}
 
Example #7
Source File: JsonWebEncryptionTest.java    From Jose4j with Apache License 2.0 6 votes vote down vote up
@Test
public void testJweExampleA3() throws JoseException
{
    // http://tools.ietf.org/html/draft-ietf-jose-json-web-encryption-14#appendix-A.3
    String jweCsFromAppdxA3 = "eyJhbGciOiJBMTI4S1ciLCJlbmMiOiJBMTI4Q0JDLUhTMjU2In0." +
            "6KB707dM9YTIgHtLvtgWQ8mKwboJW3of9locizkDTHzBC2IlrT1oOQ." +
            "AxY8DCtDaGlsbGljb3RoZQ." +
            "KDlTtXchhZTGufMYmOYGS4HffxPSUrfmqCHXaI9wOGY." +
            "U0m_YmjN04DJvceFICbCVQ";

    JsonWebEncryption jwe = new JsonWebEncryption();
    JsonWebKey jsonWebKey = JsonWebKey.Factory.newJwk("\n" +
            "{\"kty\":\"oct\",\n" +
            " \"k\":\"GawgguFyGrWKav7AX4VKUg\"\n" +
            "}");

    jwe.setCompactSerialization(jweCsFromAppdxA3);
    jwe.setKey(new AesKey(jsonWebKey.getKey().getEncoded()));

    String plaintextString = jwe.getPlaintextString();

    assertEquals("Live long and prosper.", plaintextString);
}
 
Example #8
Source File: JWTVerificationkeyResolverTest.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
@Before
@SuppressWarnings({"unchecked"})
public void setUp() throws Exception {
  super.setUp();
  k1 = new KeyHolder("k1");
  k2 = new KeyHolder("k2");
  k3 = new KeyHolder("k3");
  k4 = new KeyHolder("k4");
  k5 = new KeyHolder("k5");

  when(firstJwkList.getJsonWebKeys()).thenReturn(asList(k1.getJwk(), k2.getJwk()));
  doAnswer(invocation -> {
    keysToReturnFromSecondJwk = (List<JsonWebKey>) refreshSequenceForSecondJwk.next();
    System.out.println("Refresh called, next to return is " + keysToReturnFromSecondJwk);
    return null;
  }).when(secondJwkList).refresh();
  when(secondJwkList.getJsonWebKeys()).then(inv -> {
    if (keysToReturnFromSecondJwk == null)
      keysToReturnFromSecondJwk = (List<JsonWebKey>) refreshSequenceForSecondJwk.next();
    return keysToReturnFromSecondJwk;
  });
  when(httpsJwksFactory.createList(anyList())).thenReturn(asList(firstJwkList, secondJwkList));

  JWTIssuerConfig issuerConfig = new JWTIssuerConfig("primary").setIss("foo").setJwksUrl(asList("url1", "url2"));
  JWTIssuerConfig.setHttpsJwksFactory(httpsJwksFactory);
  resolver = new JWTVerificationkeyResolver(Arrays.asList(issuerConfig), true);

  assumeWorkingMockito();
}
 
Example #9
Source File: HeadersTest.java    From Jose4j with Apache License 2.0 5 votes vote down vote up
@Test
public void testRoundTripJwkHeader() throws JoseException
{
    Headers headers = new Headers();

    String ephemeralJwkJson = "\n{\"kty\":\"EC\",\n" +
            " \"crv\":\"P-256\",\n" +
            " \"x\":\"gI0GAILBdu7T53akrFmMyGcsF3n5dO7MmwNBHKW5SV0\",\n" +
            " \"y\":\"SLW_xSffzlPWrHEVI30DHM_4egVwt3NQqeUD7nMFpps\",\n" +
            " \"d\":\"0_NxaRPUMQoAJt50Gz8YiTr8gRTwyEaCumd-MToTmIo\"\n" +
            "}";
    PublicJsonWebKey ephemeralJwk = PublicJsonWebKey.Factory.newPublicJwk(ephemeralJwkJson);

    String name = "jwk";
    headers.setJwkHeaderValue(name, ephemeralJwk);

    JsonWebKey jwk = headers.getJwkHeaderValue(name);

    assertThat(ephemeralJwk.getKey(), is(equalTo(jwk.getKey())));

    String encodedHeader = headers.getEncodedHeader();

    Headers parsedHeaders = new Headers();
    parsedHeaders.setEncodedHeader(encodedHeader);

    JsonWebKey jwkFromParsed = parsedHeaders.getJwkHeaderValue(name);
    assertThat(ephemeralJwk.getKey(), is(equalTo(jwkFromParsed.getKey())));
}
 
Example #10
Source File: KeyLocationResolver.java    From smallrye-jwt with Apache License 2.0 5 votes vote down vote up
private static boolean isMatchingJwkAvailable(List<JsonWebKey> keys, String kid) {
    if (kid != null) {
        for (JsonWebKey currentJwk : keys) {
            if (kid.equals(currentJwk.getKeyId())) {
                return true;
            }
        }
    }
    return false;
}
 
Example #11
Source File: EcdhKeyAgreementAlgorithm.java    From Jose4j with Apache License 2.0 5 votes vote down vote up
public Key manageForDecrypt(Key managementKey, byte[] encryptedKey, ContentEncryptionKeyDescriptor cekDesc, Headers headers,  ProviderContext providerContext) throws JoseException
{
    String keyFactoryProvider = providerContext.getGeneralProviderContext().getKeyFactoryProvider();
    JsonWebKey ephemeralJwk = headers.getPublicJwkHeaderValue(HeaderParameterNames.EPHEMERAL_PUBLIC_KEY, keyFactoryProvider);
    ephemeralJwk.getKey();
    byte[] z = generateEcdhSecret((PrivateKey) managementKey, (PublicKey)ephemeralJwk.getKey(), providerContext);
    byte[] derivedKey = kdf(cekDesc, headers, z, providerContext);
    String cekAlg = cekDesc.getContentEncryptionKeyAlgorithm();
    return new SecretKeySpec(derivedKey, cekAlg);
}
 
Example #12
Source File: JwsUsingHmacSha256ExampleTest.java    From Jose4j with Apache License 2.0 5 votes vote down vote up
public void testSignExample() throws JoseException
{
    JsonWebSignature jws = new JsonWebSignature();
    jws.setPayload(PAYLOAD);

    JsonWebKey jsonWebKey = JsonWebKey.Factory.newJwk(JWK);
    jws.setKey(jsonWebKey.getKey());
    jws.getHeaders().setFullHeaderAsJsonString("{\"typ\":\"JWT\",\r\n \"alg\":\"HS256\"}");

    String compactSerialization = jws.getCompactSerialization();

    assertEquals("example jws value doesn't match calculated compact serialization", JWS, compactSerialization);
}
 
Example #13
Source File: KeyUtils.java    From smallrye-jwt with Apache License 2.0 5 votes vote down vote up
static Key getPublicOrSecretEncryptingKey(JsonWebKey currentJwk) {
    List<String> keyOps = currentJwk.getKeyOps();
    if (keyOps == null || keyOps.contains("encryption")) {
        if ("oct".equals(currentJwk.getKeyType())) {
            return OctetSequenceJsonWebKey.class.cast(currentJwk).getKey();
        } else {
            return PublicJsonWebKey.class.cast(currentJwk).getPublicKey();
        }
    }
    return null;
}
 
Example #14
Source File: KeyLocationResolverTest.java    From smallrye-jwt with Apache License 2.0 5 votes vote down vote up
@Test
public void testLoadHttpsJwksNonMathchingKidAndRefresh() throws Exception {
    JWTAuthContextInfo contextInfo = new JWTAuthContextInfo("https://github.com/my_key.jwks", "issuer");
    contextInfo.setJwksRefreshInterval(10);

    KeyLocationResolver keyLocationResolver = new KeyLocationResolver(contextInfo) {
        protected HttpsJwks initializeHttpsJwks() {
            return httpsJwks;
        }
    };
    // token 'kid' is '1'
    when(signature.getHeaders()).thenReturn(headers);
    when(headers.getStringHeaderValue(JsonWebKey.KEY_ID_PARAMETER)).thenReturn("1");

    final RsaJsonWebKey jwk = new RsaJsonWebKey(key);

    // Return JWK Set with a non-matching JWK with 'kid' set to '2' 
    jwk.setKeyId("2");
    when(httpsJwks.getJsonWebKeys()).thenReturn(Collections.singletonList(jwk));

    // Refresh JWK Set and get a matching JWK with 'kid' set to '1'
    doAnswer((i) -> {
        jwk.setKeyId("1");
        return null;
    }).when(httpsJwks).refresh();

    keyLocationResolver = Mockito.spy(keyLocationResolver);
    assertEquals(key, keyLocationResolver.resolveKey(signature, emptyList()));
    assertNull(keyLocationResolver.verificationKey);
}
 
Example #15
Source File: KeyUtils.java    From smallrye-jwt with Apache License 2.0 5 votes vote down vote up
static Key getPrivateOrSecretSigningKey(JsonWebKey currentJwk) {
    List<String> keyOps = currentJwk.getKeyOps();
    if (keyOps == null || keyOps.contains("sign")) {
        if ("oct".equals(currentJwk.getKeyType())) {
            return OctetSequenceJsonWebKey.class.cast(currentJwk).getKey();
        } else {
            return PublicJsonWebKey.class.cast(currentJwk).getPrivateKey();
        }
    }
    return null;
}
 
Example #16
Source File: KeyUtils.java    From smallrye-jwt with Apache License 2.0 5 votes vote down vote up
static Key getEncryptionKeyFromJwkSet(String kid, List<JsonWebKey> keys) {
    if (kid != null) {
        for (JsonWebKey currentJwk : keys) {
            if (kid.equals(currentJwk.getKeyId())) {
                return getPublicOrSecretEncryptingKey(currentJwk);
            }
        }
    }
    // if JWK set contains a single JWK only then try to use it
    // but only if 'kid' is not set in both the token and this JWK
    if (keys.size() == 1 && (kid == null || keys.get(0).getKeyId() == null)) {
        return getPublicOrSecretEncryptingKey(keys.get(0));
    }
    return null;
}
 
Example #17
Source File: Jose4jJWKSTest.java    From microprofile-jwt-auth with Apache License 2.0 5 votes vote down vote up
@Override
protected void validateToken(String token, URL jwksURL, String issuer, int expGracePeriodSecs) throws Exception {
    JwtConsumerBuilder builder = new JwtConsumerBuilder()
        .setRequireExpirationTime()
        .setRequireSubject()
        .setSkipDefaultAudienceValidation()
        .setExpectedIssuer(issuer)
        .setJwsAlgorithmConstraints(
            new AlgorithmConstraints(AlgorithmConstraints.ConstraintType.WHITELIST,
                                     AlgorithmIdentifiers.RSA_USING_SHA256));

    HttpsJwks keySource = new HttpsJwks(jwksURL.toExternalForm());
    List<JsonWebKey> keys = keySource.getJsonWebKeys();
    JsonWebKey key = keys.get(0);
    if(key instanceof PublicJsonWebKey) {
        PublicJsonWebKey publicJsonWebKey = (PublicJsonWebKey) key;
        PublicKey pk = publicJsonWebKey.getPublicKey();
        byte[] encoded = pk.getEncoded();
        String pem = Base64.getEncoder().encodeToString(encoded);
        System.out.printf("pk.pem: %s\n", pem);
    }
    builder.setVerificationKeyResolver(new HttpsJwksVerificationKeyResolver(keySource));

    if (expGracePeriodSecs > 0) {
        builder.setAllowedClockSkewInSeconds(expGracePeriodSecs);
    }
    else {
        builder.setEvaluationTime(NumericDate.fromSeconds(0));
    }

    JwtConsumer jwtConsumer = builder.build();
    JwtContext jwtContext = jwtConsumer.process(token);
    String type = jwtContext.getJoseObjects().get(0).getHeader("typ");
    //  Validate the JWT and process it to the Claims
    jwtConsumer.processContext(jwtContext);

}
 
Example #18
Source File: ChangingKeyTest.java    From Jose4j with Apache License 2.0 5 votes vote down vote up
@Test
public void testOnNewKey() throws Exception
{
    JsonWebKey jwk = JsonWebKey.Factory.newJwk("{\"kty\":\"oct\",\"k\":\"9el2Km2s5LHVQqUCWIdvwMsclQqQc6CwObMnCpCC8jY\"}");

    JsonWebSignature jws = new JsonWebSignature();
    jws.setCompactSerialization("eyJhbGciOiJIUzI1NiJ9.c2lnaA.2yUt5UtfsRK1pnN0KTTv7gzHTxwDqDz2OkFSqlbQ40A");
    jws.setKey(new HmacKey(new byte[32]));
    Assert.assertThat(false, CoreMatchers.equalTo(jws.verifySignature()));

    // sigh, setting a new key should now clear the little internal signature result cache...
    jws.setKey(jwk.getKey());
    Assert.assertThat(true, CoreMatchers.equalTo(jws.verifySignature()));

    jws.setKey(new HmacKey(ByteUtil.randomBytes(32)));
    Assert.assertThat(false, CoreMatchers.equalTo(jws.verifySignature()));

    jws.setKey(null);
    try
    {
        jws.verifySignature();
    }
    catch (JoseException e)
    {
        // expected
    }
}
 
Example #19
Source File: JwsUsingHmacSha256ExampleTest.java    From Jose4j with Apache License 2.0 5 votes vote down vote up
public void testVerifyExample() throws JoseException
{
    JsonWebSignature jws = new JsonWebSignature();
    jws.setCompactSerialization(JWS);
    JsonWebKey jsonWebKey = JsonWebKey.Factory.newJwk(JWK);
    jws.setKey(jsonWebKey.getKey());
    assertTrue("signature (HMAC) should validate", jws.verifySignature());
    assertEquals(PAYLOAD, jws.getPayload());
}
 
Example #20
Source File: RsaKeyManagementAlgorithm.java    From Jose4j with Apache License 2.0 5 votes vote down vote up
@Override
public boolean isAvailable()
{
    // The Sun/Oracle provider in Java 7 apparently has a defect and can’t do MGF1 with SHA-256 .
    // An exception like "java.security.InvalidKeyException: Wrapping failed ... caused by
    // javax.crypto.BadPaddingException: java.security.DigestException: Length must be at least 32 for SHA-256digests”
    // is thrown from the wrap method on the “RSA/ECB/OAEPWithSHA-256AndMGF1Padding” Cipher initialized with an
    // OAEPParameterSpec using MGF1ParameterSpec.SHA256. So actually trying it to see if it works seems like
    // the most reliable way to check for availability. Which isn’t real pretty. But hey, what can you do?
    try
    {
        JsonWebKey jwk = JsonWebKey.Factory.newJwk(
            "{\"kty\":\"RSA\"," +
            "\"n\":\"sXchDaQebHnPiGvyDOAT4saGEUetSyo9MKLOoWFsueri23bOdgWp4Dy1Wl" +
            "UzewbgBHod5pcM9H95GQRV3JDXboIRROSBigeC5yjU1hGzHHyXss8UDpre" +
            "cbAYxknTcQkhslANGRUZmdTOQ5qTRsLAt6BTYuyvVRdhS8exSZEy_c4gs_" +
            "7svlJJQ4H9_NxsiIoLwAEk7-Q3UXERGYw_75IDrGA84-lA_-Ct4eTlXHBI" +
            "Y2EaV7t7LjJaynVJCpkv4LKjTTAumiGUIuQhrNhZLuF_RJLqHpM2kgWFLU" +
            "7-VTdL1VbC2tejvcI2BlMkEpk1BzBZI0KQB0GaDWFLN-aEAw3vRw\"," +
            "\"e\":\"AQAB\"}");
        ContentEncryptionKeyDescriptor cekDesc = new ContentEncryptionKeyDescriptor(16, AesKey.ALGORITHM);
        ContentEncryptionKeys contentEncryptionKeys = manageForEncrypt(jwk.getKey(), cekDesc, null, null, new ProviderContext());
        return contentEncryptionKeys != null;
    }
    catch (JoseException e)
    {
        log.debug(getAlgorithmIdentifier() + " is not available due to " + ExceptionHelp.toStringWithCauses(e));
        return false;
    }
}
 
Example #21
Source File: JwsUsingRsaSha256ExampleTest.java    From Jose4j with Apache License 2.0 5 votes vote down vote up
public void testKey11to12() throws Exception
{
    // draft 12 used a JWK encoding of the key where previously it was octet sequences
    // and this is just a sanity check that it didn't change and my stuff sees them as the same
    // may want to redo some of the ExampleRsaKeyFromJws to just use the JWK serialization at some point
    // if private key support is added
    String jwkJson = "     {\"kty\":\"RSA\",\n" +
            "      \"n\":\"ofgWCuLjybRlzo0tZWJjNiuSfb4p4fAkd_wWJcyQoTbji9k0l8W26mPddx\n" +
            "           HmfHQp-Vaw-4qPCJrcS2mJPMEzP1Pt0Bm4d4QlL-yRT-SFd2lZS-pCgNMs\n" +
            "           D1W_YpRPEwOWvG6b32690r2jZ47soMZo9wGzjb_7OMg0LOL-bSf63kpaSH\n" +
            "           SXndS5z5rexMdbBYUsLA9e-KXBdQOS-UTo7WTBEMa2R2CapHg665xsmtdV\n" +
            "           MTBQY4uDZlxvb3qCo5ZwKh9kG4LT6_I5IhlJH7aGhyxXFvUK-DWNmoudF8\n" +
            "           NAco9_h9iaGNj8q2ethFkMLs91kzk2PAcDTW9gb54h4FRWyuXpoQ\",\n" +
            "      \"e\":\"AQAB\",\n" +
            "      \"d\":\"Eq5xpGnNCivDflJsRQBXHx1hdR1k6Ulwe2JZD50LpXyWPEAeP88vLNO97I\n" +
            "           jlA7_GQ5sLKMgvfTeXZx9SE-7YwVol2NXOoAJe46sui395IW_GO-pWJ1O0\n" +
            "           BkTGoVEn2bKVRUCgu-GjBVaYLU6f3l9kJfFNS3E0QbVdxzubSu3Mkqzjkn\n" +
            "           439X0M_V51gfpRLI9JYanrC4D4qAdGcopV_0ZHHzQlBjudU2QvXt4ehNYT\n" +
            "           CBr6XCLQUShb1juUO1ZdiYoFaFQT5Tw8bGUl_x_jTj3ccPDVZFD9pIuhLh\n" +
            "           BOneufuBiB4cS98l2SR_RQyGWSeWjnczT0QU91p1DhOVRuOopznQ\"\n" +
            "     }";
    Map<String, Object> parsed = JsonUtil.parseJson(jwkJson);
    JsonWebKey jsonWebKey = JsonWebKey.Factory.newJwk(parsed);
    assertTrue(jsonWebKey.getKey().equals(ExampleRsaKeyFromJws.PUBLIC_KEY));
    String d = (String)parsed.get("d");
    Base64Url base64Url = new Base64Url();
    byte[] privateExp = base64Url.base64UrlDecode(d);
    assertTrue(Arrays.equals(ExampleRsaKeyFromJws.D_SIGNED_BYTES, privateExp));
}
 
Example #22
Source File: JwsUsingEcdsaP521Sha512ExampleTest.java    From Jose4j with Apache License 2.0 5 votes vote down vote up
public void testVerifyExampleFromDraft14() throws JoseException
    {
        // http://www.ietf.org/mail-archive/web/jose/current/msg03018.html
        String jwsCs = "eyJhbGciOiJFUzUxMiJ9" +
                "." +
//                "eyJpc3MiOiJqb2UiLA0KICJleHAiOjEzMDA4MTkzODAsDQogImh0dHA6Ly9leGFt" +
//                "cGxlLmNvbS9pc19yb290Ijp0cnVlfQ" +
                "UGF5bG9hZA" +
                "." +
                "AdwMgeerwtHoh-l192l60hp9wAHZFVJbLfD_UxMi70cwnZOYaRI1bKPWROc-mZZq" +
                "wqT2SI-KGDKB34XO0aw_7XdtAG8GaSwFKdCAPZgoXD2YBJZCPEX3xKpRwcdOO8Kp" +
                "EHwJjyqOgzDO7iKvU8vcnwNrmxYbSW9ERBXukOXolLzeO_Jn";

        String jwkJson = "     {\"kty\":\"EC\",\n" +
                "      \"crv\":\"P-521\",\n" +
                "      \"x\":\"AekpBQ8ST8a8VcfVOTNl353vSrDCLLJXmPk06wTjxrrjcBpXp5EOnYG_\n" +
                "           NjFZ6OvLFV1jSfS9tsz4qUxcWceqwQGk\",\n" +
                "      \"y\":\"ADSmRA43Z1DSNx_RvcLI87cdL07l6jQyyBXMoxVg_l2Th-x3S1WDhjDl\n" +
                "           y79ajL4Kkd0AZMaZmh9ubmf63e3kyMj2\",\n" +
                "      \"d\":\"AY5pb7A0UFiB3RELSD64fTLOSV_jazdF7fLYyuTw8lOfRhWg6Y6rUrPA\n" +
                "           xerEzgdRhajnu0ferB0d53vM9mE15j2C\"\n" +
                "     }";

        JsonWebKey jwk = JsonWebKey.Factory.newJwk(jwkJson);

        JsonWebSignature jws = new JsonWebSignature();
        jws.setCompactSerialization(jwsCs);
        jws.setKey(jwk.getKey());
        String payload = jws.getPayload();
        System.out.println(payload);
        assertTrue("signature should validate", jws.verifySignature());
    }
 
Example #23
Source File: EcdsaUsingShaAlgorithmTest.java    From Jose4j with Apache License 2.0 5 votes vote down vote up
private void check(String jwkJson, String cs) throws JoseException
{
    JsonWebKey jwk = JsonWebKey.Factory.newJwk(jwkJson);
    JsonWebSignature jws = new JsonWebSignature();
    jws.setCompactSerialization(cs);
    jws.setKey(jwk.getKey());
    Assert.assertTrue(jws.verifySignature());
}
 
Example #24
Source File: Aes128KeyWrapManagementAlgorithmTest.java    From Jose4j with Apache License 2.0 5 votes vote down vote up
public void testJweExample() throws JoseException
{
    // Test the AES key wrap part of Example JWE using AES Key Wrap and AES_128_CBC_HMAC_SHA_256 from
    // http://tools.ietf.org/html/draft-ietf-jose-json-web-encryption-14#appendix-A.3

    int[] cekInts = {4, 211, 31, 197, 84, 157, 252, 254, 11, 100, 157, 250, 63, 170, 106,
            206, 107, 124, 212, 45, 111, 107, 9, 219, 200, 177, 0, 240, 143, 156,
            44, 207};
    byte[] cekBytes = ByteUtil.convertUnsignedToSignedTwosComp(cekInts);

    JsonWebKey jsonWebKey = JsonWebKey.Factory.newJwk("\n" +
            "     {\"kty\":\"oct\",\n" +
            "      \"k\":\"GawgguFyGrWKav7AX4VKUg\"\n" +
            "     }");
    AesKey managementKey = new AesKey(jsonWebKey.getKey().getEncoded());

    WrappingKeyManagementAlgorithm wrappingKeyManagementAlgorithm = new AesKeyWrapManagementAlgorithm.Aes128();

    ContentEncryptionAlgorithm contentEncryptionAlgorithm = new AesCbcHmacSha2ContentEncryptionAlgorithm.Aes128CbcHmacSha256();
    ContentEncryptionKeyDescriptor cekDesc = contentEncryptionAlgorithm.getContentEncryptionKeyDescriptor();

    ContentEncryptionKeys contentEncryptionKeys = wrappingKeyManagementAlgorithm.manageForEnc(managementKey, cekDesc, cekBytes, ProviderContextTest.EMPTY_CONTEXT);

    String encodedEncryptedKeyFromExample ="6KB707dM9YTIgHtLvtgWQ8mKwboJW3of9locizkDTHzBC2IlrT1oOQ";

    Base64Url u = new Base64Url();
    String encodedWrapped = u.base64UrlEncode(contentEncryptionKeys.getEncryptedKey());

    assertEquals(encodedEncryptedKeyFromExample, encodedWrapped);

    byte[] encryptedKey = u.base64UrlDecode(encodedEncryptedKeyFromExample);

    Key key = wrappingKeyManagementAlgorithm.manageForDecrypt(managementKey, encryptedKey, cekDesc, null, ProviderContextTest.EMPTY_CONTEXT);

    assertTrue(Arrays.equals(cekBytes, key.getEncoded()));
}
 
Example #25
Source File: JsonWebEncryptionTest.java    From Jose4j with Apache License 2.0 5 votes vote down vote up
@Test (expected = InvalidAlgorithmException.class)
public void testBlackListAlg() throws JoseException
{
    String jwecs = "eyJhbGciOiJkaXIiLCJlbmMiOiJBMTI4Q0JDLUhTMjU2In0..LpJAcwq3RzCs-zPRQzT-jg.IO0ZwAhWnSF05dslZwaBKcHYOAKlSpt_l7Dl5ABrUS0.0KfkxQTFqTQjzfJIm8MNjg";
    JsonWebKey jsonWebKey = JsonWebKey.Factory.newJwk("{\"kty\":\"oct\",\"k\":\"I95jRMEyRvD0t3LRgL1GSWTgkX5jznuhX4mce9bYV_A\"}");

    JsonWebEncryption jwe = new JsonWebEncryption();
    jwe.setAlgorithmConstraints(new AlgorithmConstraints(BLACKLIST, DIRECT));
    jwe.setCompactSerialization(jwecs);
    jwe.setKey(jsonWebKey.getKey());
    jwe.getPayload();
}
 
Example #26
Source File: JsonWebEncryptionTest.java    From Jose4j with Apache License 2.0 5 votes vote down vote up
@Test (expected = InvalidAlgorithmException.class)
public void testBlackListEncAlg() throws JoseException
{
    String jwecs = "eyJhbGciOiJkaXIiLCJlbmMiOiJBMTI4Q0JDLUhTMjU2In0..LpJAcwq3RzCs-zPRQzT-jg.IO0ZwAhWnSF05dslZwaBKcHYOAKlSpt_l7Dl5ABrUS0.0KfkxQTFqTQjzfJIm8MNjg";
    JsonWebKey jsonWebKey = JsonWebKey.Factory.newJwk("{\"kty\":\"oct\",\"k\":\"I95jRMEyRvD0t3LRgL1GSWTgkX5jznuhX4mce9bYV_A\"}");

    JsonWebEncryption jwe = new JsonWebEncryption();
    jwe.setContentEncryptionAlgorithmConstraints(new AlgorithmConstraints(BLACKLIST, AES_128_CBC_HMAC_SHA_256));
    jwe.setCompactSerialization(jwecs);
    jwe.setKey(jsonWebKey.getKey());
    jwe.getPayload();
}
 
Example #27
Source File: JweEncryptorCallout.java    From iloveapis2015-jwt-jwe-jws with Apache License 2.0 5 votes vote down vote up
public ExecutionResult execute(MessageContext msgCtxt, ExecutionContext exeCtxt)
{
    try {
        msgCtxt.removeVariable(varName("error"));
        String plaintext = getPlainText(msgCtxt);
        String secretKey = getSecretKey(msgCtxt);
        String algorithm = getAlgorithm(msgCtxt);
        String b64Key = Base64.encodeBase64String(secretKey.getBytes("UTF-8"));

        String jwkJson = "{\"kty\":\"oct\",\"k\":\""+ b64Key + "\"}";
        JsonWebKey jwk = JsonWebKey.Factory.newJwk(jwkJson);

        JsonWebEncryption jwe = new JsonWebEncryption();
        jwe.setPlaintext(plaintext);
        jwe.setEncryptionMethodHeaderParameter(algorithm);
        jwe.setAlgorithmHeaderValue(KeyManagementAlgorithmIdentifiers.PBES2_HS256_A128KW);
        jwe.setKey(jwk.getKey());
        // do the encryption
        String compactSerialization = jwe.getCompactSerialization();
        msgCtxt.setVariable(varName("jwe"), compactSerialization);
    }
    catch (Exception e) {
        //e.printStackTrace();
        msgCtxt.setVariable(varName("error"), "Exception " + e.toString());
        msgCtxt.setVariable(varName("stacktrace"), ExceptionUtils.getStackTrace(e));
        return ExecutionResult.ABORT;
    }
    return ExecutionResult.SUCCESS;
}
 
Example #28
Source File: JwtHelper.java    From openhab-core with Eclipse Public License 2.0 5 votes vote down vote up
private RsaJsonWebKey loadOrGenerateKey() throws FileNotFoundException, JoseException, IOException {
    try (final BufferedReader reader = Files.newBufferedReader(Paths.get(KEY_FILE_PATH))) {
        return (RsaJsonWebKey) JsonWebKey.Factory.newJwk(reader.readLine());
    } catch (IOException | JoseException e) {
        RsaJsonWebKey key = generateNewKey();
        logger.debug("Created JWT signature key in {}", KEY_FILE_PATH);
        return key;
    }
}
 
Example #29
Source File: DefaultCipherExecutor.java    From nano-framework with Apache License 2.0 5 votes vote down vote up
/**
 * Prepare json web token key.
 *
 * @param secret the secret
 * @return the key
 */
private Key prepareJsonWebTokenKey(final String secret) {
    try {
        final Map<String, Object> keys = new HashMap<>(2);
        keys.put("kty", "oct");
        keys.put("k", secret);
        final JsonWebKey jwk = JsonWebKey.Factory.newJwk(keys);
        return jwk.getKey();
    } catch (final Exception e) {
        throw new IllegalArgumentException(e.getMessage(), e);
    }
}
 
Example #30
Source File: JWTAuthConfiguration.java    From tomee with Apache License 2.0 5 votes vote down vote up
public List<JsonWebKey> getPublicKeys() {
    return publicKeys.entrySet().stream().map(key -> {
        try {
            final JsonWebKey jsonWebKey = JsonWebKey.Factory.newJwk(key.getValue());
            jsonWebKey.setKeyId(key.getKey());
            return jsonWebKey;
        } catch (final JoseException e) {
            logger.warning(e.getMessage());
            return null;
        }
    }).collect(Collectors.toList());
}