org.jose4j.jwk.PublicJsonWebKey Java Examples

The following examples show how to use org.jose4j.jwk.PublicJsonWebKey. 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: EcdhKeyAgreementAlgorithmTest.java    From Jose4j with Apache License 2.0 6 votes vote down vote up
public void testDecryptPrecomputedP521_ECDHandAES_256_CBC_HMAC_SHA_512() throws Exception
{
    PublicJsonWebKey jwk = PublicJsonWebKey.Factory.newPublicJwk("{\"kty\":\"EC\"," +
            "\"x\":\"AH3rqSYjKue50ThW0qq_qQ76cNtqWrc7hU6kZR6akxy8iTf8ugcpqnbgbi98AgSwIqgJZDBMCk-8eoiGaf3R_kDD\"," +
            "\"y\":\"AeafPdJjHLf6pK5V7iyMsL3-6MShpHS6jXQ8m-Bcbp06yxAMn6TJbdkacvj45dy_pdh1s6XZwoxRxNETg_gj-hq9\"," +
            "\"crv\":\"P-521\"," +
            "\"d\":\"AB2tm9vgGe2BaxZmJQ016GY-U7NV_EWhrPsLDC5l9tAM9DGEwI2cT2HcO20Z6CQndw0ZhqLZ6MEvS8siL-SCxIl2\"}\n");
    JsonWebEncryption jwe = new JsonWebEncryption();
    String cs = "eyJlbmMiOiJBMjU2Q0JDLUhTNTEyIiwiYWxnIjoiRUNESC1FUyIsImVwayI6eyJrdHkiOiJFQyIsIngiOiJBQ1RLMlVPSjJ6SVk3U1U4T0xkaG1QQmE4ZUVpd2JrX0" +
            "9UMXE0MHBsRlRwQmJKUXg3YWdqWG9LYml2NS1OTXB6eXZySm1rblM3SjNRUWlUeFgwWmtjemhEIiwieSI6IkFXeTZCR1dkZld2ekVNeGIxQklCQnZmRDJ4bEh6Rjk2YzVVR" +
            "VQ4SFBUS0RSeUJyMnQ4T2dTX1J2MnNoUmxGbXlqUWpyX25uQk94akcxVTZNWDNlZ2VETzciLCJjcnYiOiJQLTUyMSJ9fQ..EWqSGntxbO_Y_6JRjFkCgg.DGjDNjAYdsnYT" +
            "pUFJi1gEI4YtNd7gBPMjD3CDH047RAwZKTme6Ah_ztzxSfVg5kG.yGm5jn2LtbFXaK_yf0b0932sI2O77j2gwmL1Y09YC_Y";
    jwe.setCompactSerialization(cs);
    jwe.setKey(jwk.getPrivateKey());
    assertEquals("And also the working here would be nice.", jwe.getPayload());
}
 
Example #3
Source File: EcdhKeyAgreementAlgorithmTest.java    From Jose4j with Apache License 2.0 6 votes vote down vote up
public void testDecryptPrecomputedP256_ECDHandAES_256_CBC_HMAC_SHA_512() throws Exception
{
    PublicJsonWebKey jwk = PublicJsonWebKey.Factory.newPublicJwk("{\"kty\":\"EC\",\"x\":\"fXx-DfOsmecjKh3VrLZFsF98Z1nutsL4UdFTdgA8S7Y\"," +
            "\"y\":\"LGzyJY99aqKk52UIExcNFSTs0S7HnNzQ-DRWBTHDad4\",\"crv\":\"P-256\",\"d\":\"OeVCWbXuFuJ9U16q7bhLNoKPLLnK-yTx95grzfvQ2l4\"}");
    JsonWebEncryption jwe = new JsonWebEncryption();
    String cs =
            "eyJlbmMiOiJBMjU2Q0JDLUhTNTEyIiwiYWxnIjoiRUNESC1FUyIsImVwayI6eyJrdHkiOiJFQyIsIngiOiJ3ZlRHNVFHZkItNHUxanVUUEN1aTNESXhFTV" +
                    "82ZUs5ZEk5TXNZckpxWDRnIiwieSI6Ik8yanlRbHQ2TXFGTGtqMWFCWW1aNXZJWHFVRHh6Ulk3dER0WmdZUUVNa0kiLCJjcnYiOiJQLTI1NiJ9fQ." +
                    "." +
                    "mk4wQzGSSeZ8uSgEYTIetA." +
                    "fCw3-TosL4p0D5fEXw0bEA." +
                    "9mPsdmGTVoVexXqEOdN5VUKk-ZNtfOtUfbdjVHoko_o";
    jwe.setCompactSerialization(cs);
    jwe.setKey(jwk.getPrivateKey());
    assertEquals("It works!", jwe.getPayload());
}
 
Example #4
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 #5
Source File: CrossEncryptionTest.java    From oxAuth with MIT License 5 votes vote down vote up
public boolean testDecryptWithJose4J(String jwe) {

        try {

            PublicJsonWebKey jwk = PublicJsonWebKey.Factory.newPublicJwk(recipientJwkJson);

            JsonWebEncryption receiverJwe = new JsonWebEncryption();

            AlgorithmConstraints algConstraints = new AlgorithmConstraints(ConstraintType.WHITELIST, KeyManagementAlgorithmIdentifiers.RSA_OAEP);
            receiverJwe.setAlgorithmConstraints(algConstraints);
            AlgorithmConstraints encConstraints = new AlgorithmConstraints(ConstraintType.WHITELIST, ContentEncryptionAlgorithmIdentifiers.AES_128_GCM);
            receiverJwe.setContentEncryptionAlgorithmConstraints(encConstraints);

            receiverJwe.setKey(jwk.getPrivateKey());

            receiverJwe.setCompactSerialization(jwe);
            final String decryptedPayload = new String(Base64Util.base64urldecode(receiverJwe.getPlaintextString()));
            System.out.println("Jose4j decrypt succeed: " + decryptedPayload);
            if (isJsonEqual(decryptedPayload, PAYLOAD)) {
                return true;
            }
        } catch (Exception e) {
            System.out.println("Jose4j decrypt failed: " + e.getMessage());
            e.printStackTrace();
        }
        return false;
    }
 
Example #6
Source File: KeyPairUtilTest.java    From Jose4j with Apache License 2.0 5 votes vote down vote up
@Test
public void rsaPublicKeyEncodingDecodingAndSign() throws Exception
{
    PublicJsonWebKey publicJsonWebKey = ExampleRsaJwksFromJwe.APPENDIX_A_1;
    String pem = KeyPairUtil.pemEncode(publicJsonWebKey.getPublicKey());
    String expectedPem = "-----BEGIN PUBLIC KEY-----\r\n" +
            "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAoahUIoWw0K0usKNuOR6H\r\n" +
            "4wkf4oBUXHTxRvgb48E+BVvxkeDNjbC4he8rUWcJoZmds2h7M70imEVhRU5djINX\r\n" +
            "tqllXI4DFqcI1DgjT9LewND8MW2Krf3Spsk/ZkoFnilakGygTwpZ3uesH+PFABNI\r\n" +
            "UYpOiN15dsQRkgr0vEhxN92i2asbOenSZeyaxziK72UwxrrKoExv6kc5twXTq4h+\r\n" +
            "QChLOln0/mtUZwfsRaMStPs6mS6XrgxnxbWhojf663tuEQueGC+FCMfra36C9knD\r\n" +
            "FGzKsNa7LZK2djYgyD3JR/MB/4NUJW/TqOQtwHYbxevoJArm+L5StowjzGy+/bq6\r\n" +
            "GwIDAQAB\r\n" +
            "-----END PUBLIC KEY-----";
    Assert.assertThat(pem, equalTo(expectedPem));


    RsaKeyUtil rsaKeyUtil = new RsaKeyUtil();
    PublicKey publicKey = rsaKeyUtil.fromPemEncoded(pem);
    Assert.assertThat(publicKey, equalTo(publicJsonWebKey.getPublicKey()));

    JwtClaims claims = new JwtClaims();
    claims.setSubject("meh");
    claims.setExpirationTimeMinutesInTheFuture(20);
    claims.setGeneratedJwtId();
    claims.setAudience("you");
    claims.setIssuer("me");
    JsonWebSignature jws = new JsonWebSignature();
    jws.setPayload(claims.toJson());
    jws.setKey(publicJsonWebKey.getPrivateKey());
    jws.setAlgorithmHeaderValue(AlgorithmIdentifiers.RSA_USING_SHA256);
    String jwt = jws.getCompactSerialization();

    Logger log = LoggerFactory.getLogger(this.getClass());
    log.debug("The following JWT and public key should be (and were on 11/11/15) usable and produce a valid " +
            "result at jwt.io (related to http://stackoverflow.com/questions/32744172):\n" + jwt + "\n" + pem);
}
 
Example #7
Source File: EcdhKeyAgreementAlgorithmTest.java    From Jose4j with Apache License 2.0 5 votes vote down vote up
public void testDecryptPrecomputedP384_ECDHandAES_192_CBC_HMAC_SHA_384() throws Exception
{
    PublicJsonWebKey jwk = PublicJsonWebKey.Factory.newPublicJwk("{\"kty\":\"EC\",\"x\":\"nBr92fh2JsEjIF1LR5PKICBeHNIBe0xb7nlBrrU3WoWgfJYfXve1jxC-5VT5EPLt\"," +
            "\"y\":\"sUAxL3L5lJdzFUSR9EHLniuBhEbvXfPa_3OiR6Du0_GOlFXXIi4UmbNpk10_Thfq\"," +
            "\"crv\":\"P-384\",\"d\":\"0f0NnWg__Qgqjj3fl2gAlsID4Ni41FR88cmZPVgb6ch-ZShuVJRjoxymCuzVP7Gi\"}");
    JsonWebEncryption jwe = new JsonWebEncryption();
    String cs = "eyJlbmMiOiJBMTkyQ0JDLUhTMzg0IiwiYWxnIjoiRUNESC1FUyIsImVwayI6eyJrdHkiOiJFQyIsIngiOiJsX3hXdzIyb1N" +
            "fOWZGbV96amNzYkstd3R3d0RHSlRQLUxnNFVBWDI3WWF1b1YwNml2emwtcm1ra2h6ci11SDBmIiwieSI6IloyYmVn" +
            "bzBqeE9nY0YtNVp4SFNBOU5jZDVCOW8wUE1pSVlRbm9sWkNQTHA3YndPd1RLUEZaaFZVUlFPSjdoeUciLCJjcnYiOiJQLTM4NCJ9fQ." +
            ".jSWP7pfa4KcpqKWZ1x8awg.osb-5641Ej1Uon_f3U8bNw.KUQWwb35Gxq3YQ34_AVkebugx4rxq1lO\n";
    jwe.setCompactSerialization(cs);
    jwe.setKey(jwk.getPrivateKey());
    assertEquals("Please work...", jwe.getPayload());
}
 
Example #8
Source File: Pbes2ExampleEncryptedRSAPrivateKeyJwkAppendixCTest.java    From Jose4j with Apache License 2.0 5 votes vote down vote up
@Test
public void decryptExample() throws JoseException
{
    PbkdfKey key = new PbkdfKey(PASSWORD);
    JsonWebEncryption jwe = new JsonWebEncryption();
    jwe.setCompactSerialization(CS);
    jwe.setKey(key);
    String payload = jwe.getPayload();
    PublicJsonWebKey jwk = PublicJsonWebKey.Factory.newPublicJwk(payload);
    assertThat("[email protected]", is(equalTo(jwk.getKeyId())));
    assertThat(RsaJsonWebKey.KEY_TYPE, is(equalTo(jwk.getKeyType())));
    assertThat(Use.ENCRYPTION, is(equalTo(jwk.getUse())));
}
 
Example #9
Source File: RsaOaepKeyManagementAlgorithmTest.java    From Jose4j with Apache License 2.0 5 votes vote down vote up
@Test
public void testWorkingExampleFromMailList() throws Exception
{
    // http://www.ietf.org/mail-archive/web/jose/current/msg04131.html
    // okay it's my own example but it's all I've got right now
    final String cs =
        "eyJhbGciOiJSU0EtT0FFUC0yNTYiLCJlbmMiOiJBMTI4Q0JDLUhTMjU2In0." +
        "fL5IL5cMCjjU9G9_ZjsD2XO0HIwTOwbVwulcZVw31_rx2qTcHzbYhIvrvbcVLTfJzn8xbQ3UEL442ZgZ1PcFYKENYePXiEyvYxPN8dmvj_" +
        "OfLSJDEqR6kvwOb6nghGtxfzdB_VRvFt2eehbCA3gWpiOYHHvSTFdBPGx2KZHQisLz3oZR8EWiZ1woEpHy8a7FoQ2zzuDlZEJQOUrh09b_" +
        "EJxmcE2jL6wmEtgabyxy3VgWg3GqSPUISlJZV9HThuVJezzktJdpntRDnAPUqjc8IwByGpMleIQcPuBUseRRPr_OsroOJ6eTl5DuFCmBOKb-eNNw5v-GEcVYr1w7X9oXoA." +
        "0frdIwx8P8UAzh1s9_PgOA." +
        "RAzILH0xfs0yxzML1CzzGExCfE2_wzWKs0FVuXfM8R5H68yTqTbqIqRCp2feAH5GSvluzmztk2_CkGNSjAyoaw." +
        "4nMUXOgmgWvM-08tIZ-h5w";

    JceProviderTestSupport jceProviderTestSupport = new JceProviderTestSupport();
    jceProviderTestSupport.setKeyManagementAlgsNeeded(KeyManagementAlgorithmIdentifiers.RSA_OAEP_256);
    jceProviderTestSupport.runWithBouncyCastleProviderIfNeeded(new JceProviderTestSupport.RunnableTest()
    {
        @Override
        public void runTest() throws Exception
        {
            if (!doubleCheckRsaOaep256())
            {
                return;
            }

            RsaJsonWebKey jwk = (RsaJsonWebKey) PublicJsonWebKey.Factory.newPublicJwk(JWK_JSON);
            JsonWebEncryption jwe = new JsonWebEncryption();
            jwe.setCompactSerialization(cs);
            jwe.setKey(jwk.getPrivateKey());
            String payloadOut = jwe.getPayload();
            assertEquals(EXAMPLE_PAYLOAD, payloadOut);
        }
    });
}
 
Example #10
Source File: RsaOaepKeyManagementAlgorithmTest.java    From Jose4j with Apache License 2.0 5 votes vote down vote up
@Test
public void test256RoundTrip() throws Exception
{
    JceProviderTestSupport jceProviderTestSupport = new JceProviderTestSupport();
    jceProviderTestSupport.setKeyManagementAlgsNeeded(KeyManagementAlgorithmIdentifiers.RSA_OAEP_256);
    jceProviderTestSupport.runWithBouncyCastleProviderIfNeeded(new JceProviderTestSupport.RunnableTest()
    {
        @Override
        public void runTest() throws Exception
        {
            if (!doubleCheckRsaOaep256())
            {
                return;
            }

            RsaJsonWebKey jwk = (RsaJsonWebKey) PublicJsonWebKey.Factory.newPublicJwk(JWK_JSON);
            JsonWebEncryption jwe = new JsonWebEncryption();
            jwe.setAlgorithmHeaderValue(KeyManagementAlgorithmIdentifiers.RSA_OAEP_256);
            jwe.setEncryptionMethodHeaderParameter(ContentEncryptionAlgorithmIdentifiers.AES_128_CBC_HMAC_SHA_256);
            jwe.setKey(jwk.getPublicKey());
            String payloadIn = EXAMPLE_PAYLOAD;
            jwe.setPayload(payloadIn);
            String compactSerialization = jwe.getCompactSerialization();
            jwe = new JsonWebEncryption();
            jwe.setCompactSerialization(compactSerialization);
            jwe.setKey(jwk.getPrivateKey());
            String payloadOut = jwe.getPayload();
            assertEquals(payloadIn, payloadOut);
        }
    });
}
 
Example #11
Source File: EcdhKeyAgreementWithAesKeyWrapAlgorithmTest.java    From Jose4j with Apache License 2.0 5 votes vote down vote up
private void jweRoundTrip(String alg, String enc) throws JoseException
{
    JsonWebEncryption jwe = new JsonWebEncryption();

    String receiverJwkJson = "\n{\"kty\":\"EC\",\n" +
            " \"crv\":\"P-256\",\n" +
            " \"x\":\"weNJy2HscCSM6AEDTDg04biOvhFhyyWvOHQfeF_PxMQ\",\n" +
            " \"y\":\"e8lnCO-AlStT-NJVX-crhB7QRYhiix03illJOVAOyck\",\n" +
            " \"d\":\"VEmDZpDXXK8p8N0Cndsxs924q6nS1RXFASRl6BfUqdw\"\n" +
            "}";
    PublicJsonWebKey receiverJwk = PublicJsonWebKey.Factory.newPublicJwk(receiverJwkJson);

    jwe.setAlgorithmHeaderValue(alg);
    jwe.setEncryptionMethodHeaderParameter(enc);
    String plaintext = "Gambling is illegal at Bushwood sir, and I never slice.";
    jwe.setPlaintext(plaintext);

    jwe.setKey(receiverJwk.getPublicKey());

    String compactSerialization = jwe.getCompactSerialization();

    log.debug("JWE w/ {} & {}: {}", alg, enc, compactSerialization);

    JsonWebEncryption receiverJwe = new JsonWebEncryption();
    receiverJwe.setCompactSerialization(compactSerialization);
    receiverJwe.setKey(receiverJwk.getPrivateKey());

    assertEquals(plaintext, receiverJwe.getPlaintextString());
}
 
Example #12
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 #13
Source File: JwtConsumerTest.java    From Jose4j with Apache License 2.0 5 votes vote down vote up
@Test
public void nestedBackwards() throws Exception
{
    // a JWT that's a JWE inside a JWS, which is unusual but legal
    String jwt = "eyJjdHkiOiJKV1QiLCJhbGciOiJFUzI1NiJ9.ZXlKNmFYQWlPaUpFUlVZaUxDSmhiR2NpT2lKRlEwUklMVVZUSWl3aVpXNWpJam9pUVRFeU9FTkNReTFJVXpJMU5pSXNJbVZ3YXlJNmV5SnJkSGtpT2lKRlF5SXNJbmdpT2lKYVIwczNWbkZOUzNKV1VGcEphRXc1UkRsT05tTnpNV0ZhYlU5MVpqbHlUWGhtUm1kRFVURjFaREJuSWl3aWVTSTZJbTAyZW01VlQybEtjMnMwTlRaRVVWb3RjVTEzZEVKblpqQkRNVXh4VDB0dk5HYzNjakpGUTBkQllUZ2lMQ0pqY25ZaU9pSlFMVEkxTmlKOWZRLi4xSndRWThoVFJVczdUMFNpOWM1VE9RLkFOdUpNcFowTU1KLTBrbVdvVHhvRDlxLTA1YUxrMkpvRzMxLXdVZ01ZakdaaWZiWG96SDEzZGRuaXZpWXNtenhMcFdVNU1lQnptN3J3TExTeUlCdjB3LmVEb1lFTEhFWXBnMHFpRzBaeHUtWEE.NctFu0mNSArPnMXakIMQKagWyU4v7733dNhDNK3KwiFP2MahpfaH0LA7x0knRk0sjASRxDuEIW6UZGfPTFOjkw";

    PublicJsonWebKey sigKey = PublicJsonWebKey.Factory.newPublicJwk("{\"kty\":\"EC\",\"x\":\"HVDkXtG_j_JQUm_mNaRPSbsEhr6gdK0a6H4EURypTU0\",\"y\":\"NxdYFS2hl1w8VKf5UTpGXh2YR7KQ8gSBIHu64W0mK8M\",\"crv\":\"P-256\",\"d\":\"ToqTlgJLhI7AQYNLesI2i-08JuaYm2wxTCDiF-VxY4A\"}");
    PublicJsonWebKey encKey = PublicJsonWebKey.Factory.newPublicJwk("{\"kty\":\"EC\",\"x\":\"7kaETHB4U9pCdsErbjw11HGv8xcQUmFy3NMuBa_J7Os\",\"y\":\"FZK-vSMpKk9gLWC5wdFjG1W_C7vgJtdm1YfNPZevmCw\",\"crv\":\"P-256\",\"d\":\"spOxtF0qiKrrCTaUs_G04RISjCx7HEgje_I7aihXVMY\"}");

    JwtConsumer firstPassConsumer = new JwtConsumerBuilder()
            .setDecryptionKey(encKey.getPrivateKey())
            .setSkipAllValidators()
            .setDisableRequireSignature()
            .setSkipSignatureVerification()
            .build();
    JwtContext jwtContext = firstPassConsumer.process(jwt);

    JwtConsumer consumer = new JwtConsumerBuilder()
            .setDecryptionKey(encKey.getPrivateKey())
            .setVerificationKey(sigKey.getPublicKey())
            .setEvaluationTime(NumericDate.fromSeconds(1420226222))
            .setExpectedAudience("canada")
            .setExpectedIssuer("usa")
            .setRequireExpirationTime()
            .build();
    JwtContext ctx = consumer.process(jwt);
    consumer.processContext(jwtContext);

    for (JwtContext context : new JwtContext[] {ctx, jwtContext})
    {
        JwtClaims jwtClaims = context.getJwtClaims();
        Assert.assertThat("eh", equalTo(jwtClaims.getStringClaimValue("message")));
        List<JsonWebStructure> joseObjects = context.getJoseObjects();
        assertThat(2, equalTo(joseObjects.size()));
        assertTrue(joseObjects.get(0) instanceof JsonWebEncryption);
        assertTrue(joseObjects.get(1) instanceof JsonWebSignature);
    }

}
 
Example #14
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 #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: DecryptAetIdentifiersTest.java    From gcp-ingestion with Mozilla Public License 2.0 5 votes vote down vote up
private static String encryptWithTestPublicKey(String payload) throws Exception {
  PublicJsonWebKey key = loadPublicKey("account-ecosystem/testkey1.public.json");
  JsonWebEncryption jwe = new JsonWebEncryption();
  jwe.setKey(key.getKey());
  jwe.setKeyIdHeaderValue(key.getKeyId());
  jwe.setAlgorithmHeaderValue(KeyManagementAlgorithmIdentifiers.ECDH_ES_A256KW);
  jwe.setEncryptionMethodHeaderParameter(ContentEncryptionAlgorithmIdentifiers.AES_256_GCM);
  jwe.setPayload(payload);
  return jwe.getCompactSerialization();
}
 
Example #17
Source File: EcdhKeyAgreementAlgorithm.java    From Jose4j with Apache License 2.0 5 votes vote down vote up
ContentEncryptionKeys manageForEncrypt(Key managementKey, ContentEncryptionKeyDescriptor cekDesc, Headers headers, PublicJsonWebKey ephemeralJwk, ProviderContext providerContext) throws JoseException
{
    headers.setJwkHeaderValue(HeaderParameterNames.EPHEMERAL_PUBLIC_KEY, ephemeralJwk);
    byte[] z = generateEcdhSecret(ephemeralJwk.getPrivateKey(), (PublicKey) managementKey, providerContext);
    byte[] derivedKey = kdf(cekDesc, headers, z, providerContext);
    return new ContentEncryptionKeys(derivedKey, null);
}
 
Example #18
Source File: Headers.java    From Jose4j with Apache License 2.0 4 votes vote down vote up
public PublicJsonWebKey getPublicJwkHeaderValue(String name, String jcaProvider) throws JoseException
{
    Object objectHeaderValue = getObjectHeaderValue(name);
    Map<String, Object> jwkParams = (Map<String, Object>) objectHeaderValue;
    return PublicJsonWebKey.Factory.newPublicJwk(jwkParams, jcaProvider);
}
 
Example #19
Source File: JwtConsumerTest.java    From Jose4j with Apache License 2.0 4 votes vote down vote up
@Test
public void tripleNesting() throws Exception
{
    // a JWT that's a JWE inside a JWS, which is unusual but legal
    String jwt = "eyJhbGciOiJQQkVTMi1IUzI1NitBMTI4S1ciLCJlbmMiOiJBMTI4Q0JDLUhTMjU2IiwiY3R5Ijoiand0IiwicDJjIjo4MTkyLCJwMnMiOiJiWE13N0F3YUtITWZ4cWRNIn0.5Qo4mtR0E6AnTsiq-hcH9_RJoZwmWiMl0se_riEr1sdz2IXA-vCkrw.iA7lBH3Tzs4uIJVtekZEfg.jkdleffS8GIen_xt_g3QHAc0cat6UBAODpv6WLJ_ytMw-h0dtV0F77d7k1oWxBQ68Ff83v3Pxsyiqf6K9BQUVyzmI6rZafDStQm1IdTS-rvsiB4qDrx9juMqzu1udPy5N7JGs_CDV31Ky3fWEveAy4kBX46-axdyhP5XFg6xMfJ614mcf_bfo5hIJByZFwqNolNwsHLUTuiUBa4Mdg-tfob692-ox8B2c6w4RqRrLOVA_M3gENoxbLIJGL0WL1OkdQb7fyEsaMzR3urJL1t8LI5Q1pD8wjbiv4VKvc1BqoJSM0h9mLm_GNhTdQGPmevBwWVZ1k1tWJjQw0nU2eFZJi1STDGzK1GRDBD91rZSYD763WHADbxcqxrcri92jtyZrxB22pJXEgkpMlUkxqjCFATV20WSM8aSW4Od9Of9MCnrNTIby_3np4zEq5EpFEkVmH-9PzalKWo5gOHR8Zqnldyz6xcOamP34o_lEh5ddEwAFjGTlJWrDkssMeBjOog3_CXHZhutD9IfCKmIHu6Wk10XkELamiKPmNCe_CMDEdx6o6LrCtfyheOfgpDaZeZZc3Y-TF1o9J3RmCZqB-oHgLEc9mZQrGU6r5UZ4lYyfrAJl2y7Rya87LBGsUjSs7SuIyQKYkH5ek8j_9rhm_3nZhivDchkiWx5J3Pzso5Q3p6hjUfvhpgO2ywtnii45iINi5UAL6O8xqUhxZUJSoMxt1XKwx92bmC9kOoF1ljLm-w.VP_VFGef9SGdxoHCZ01FxQ";

    PublicJsonWebKey sigKey = PublicJsonWebKey.Factory.newPublicJwk("{\"kty\":\"EC\",\"x\":\"HVDkXtG_j_JQUm_mNaRPSbsEhr6gdK0a6H4EURypTU0\",\"y\":\"NxdYFS2hl1w8VKf5UTpGXh2YR7KQ8gSBIHu64W0mK8M\",\"crv\":\"P-256\",\"d\":\"ToqTlgJLhI7AQYNLesI2i-08JuaYm2wxTCDiF-VxY4A\"}");
    final PublicJsonWebKey encKey = PublicJsonWebKey.Factory.newPublicJwk("{\"kty\":\"EC\",\"x\":\"7kaETHB4U9pCdsErbjw11HGv8xcQUmFy3NMuBa_J7Os\",\"y\":\"FZK-vSMpKk9gLWC5wdFjG1W_C7vgJtdm1YfNPZevmCw\",\"crv\":\"P-256\",\"d\":\"spOxtF0qiKrrCTaUs_G04RISjCx7HEgje_I7aihXVMY\"}");
    final Key passwordIsTaco = new PbkdfKey("taco");

    DecryptionKeyResolver decryptionKeyResolver = new DecryptionKeyResolver()
    {
        @Override
        public Key resolveKey(JsonWebEncryption jwe, List<JsonWebStructure> nestingContext) throws UnresolvableKeyException
        {
            return nestingContext.isEmpty() ? passwordIsTaco : encKey.getPrivateKey();
        }
    };

    JwtConsumer firstPassConsumer = new JwtConsumerBuilder()
            .setDecryptionKeyResolver(decryptionKeyResolver)
            .setSkipAllValidators()
            .setDisableRequireSignature()
            .setSkipSignatureVerification()
            .build();
    JwtContext jwtContext = firstPassConsumer.process(jwt);

    JwtConsumer consumer = new JwtConsumerBuilder()
            .setDecryptionKeyResolver(decryptionKeyResolver)
            .setVerificationKey(sigKey.getPublicKey())
            .setEvaluationTime(NumericDate.fromSeconds(1420229816))
            .setExpectedAudience("canada")
            .setExpectedIssuer("usa")
            .setRequireExpirationTime()
            .build();
    JwtContext ctx = consumer.process(jwt);
    consumer.processContext(jwtContext);

    for (JwtContext context : new JwtContext[] {ctx, jwtContext})
    {
        JwtClaims jwtClaims = context.getJwtClaims();
        Assert.assertThat("eh", equalTo(jwtClaims.getStringClaimValue("message")));
        List<JsonWebStructure> joseObjects = context.getJoseObjects();
        assertThat(3, equalTo(joseObjects.size()));
        assertTrue(joseObjects.get(2) instanceof JsonWebEncryption);
        assertTrue(joseObjects.get(1) instanceof JsonWebEncryption);
        assertTrue(joseObjects.get(0) instanceof JsonWebSignature);
    }

}
 
Example #20
Source File: JwtConsumerTest.java    From Jose4j with Apache License 2.0 4 votes vote down vote up
@Test
public void testOnlyEncrypted() throws Exception
{
    // there are legitimate cases where a JWT need only be encrypted but the majority of time a mac'd or signed JWS is needed
    // by default the JwtConsumer should not accept a JWE only JWT to protect against cases where integrity protection might
    // be accidentally inferred

    PublicJsonWebKey sigKey = PublicJsonWebKey.Factory.newPublicJwk("{\"kty\":\"EC\",\"x\":\"HVDkXtG_j_JQUm_mNaRPSbsEhr6gdK0a6H4EURypTU0\",\"y\":\"NxdYFS2hl1w8VKf5UTpGXh2YR7KQ8gSBIHu64W0mK8M\",\"crv\":\"P-256\",\"d\":\"ToqTlgJLhI7AQYNLesI2i-08JuaYm2wxTCDiF-VxY4A\"}");
    PublicJsonWebKey encKey = PublicJsonWebKey.Factory.newPublicJwk("{\"kty\":\"EC\",\"x\":\"7kaETHB4U9pCdsErbjw11HGv8xcQUmFy3NMuBa_J7Os\",\"y\":\"FZK-vSMpKk9gLWC5wdFjG1W_C7vgJtdm1YfNPZevmCw\",\"crv\":\"P-256\",\"d\":\"spOxtF0qiKrrCTaUs_G04RISjCx7HEgje_I7aihXVMY\"}");

    String jwt = "eyJ6aXAiOiJERUYiLCJhbGciOiJFQ0RILUVTIiwiZW5jIjoiQTEyOENCQy1IUzI1NiIsImVwayI6eyJrdHkiOiJFQyIsIngiOiJ3UXdIa1RUci1tUFpaZURDYU8wRjEwNi1NTkg0aFBfX0xrTW5MaElkTVhVIiwieSI6IkF4Ul9VNW1EN1FhMnFia3R5WS0tU1dsMng0N1gxTWJ5S2Rxb1JteUFVS1UiLCJjcnYiOiJQLTI1NiJ9fQ..oeYI_sIoU1LWIUw3z16V_g.J_BlS-qDJnAqw9wzngIQQioTbTGbyFnorVRq1WTO3leFXKKuBmqoWPHqoVSZdzsVeiFkI-F1DesY489MltwGYg.egjQH2w4oHpMgfjg8saXxQ";

    JwtConsumer firstPassConsumer = new JwtConsumerBuilder()
            .setDecryptionKey(encKey.getPrivateKey())
            .setSkipAllValidators()
            .setDisableRequireSignature()
            .setSkipSignatureVerification()
            .build();
    JwtContext jwtContext = firstPassConsumer.process(jwt);
    Assert.assertThat("eh", equalTo(jwtContext.getJwtClaims().getStringClaimValue("message")));

    JwtConsumer consumer = new JwtConsumerBuilder()
            .setDecryptionKey(encKey.getPrivateKey())
            .setVerificationKey(sigKey.getPublicKey())
            .setEvaluationTime(NumericDate.fromSeconds(1420219088))
            .setExpectedAudience("canada")
            .setExpectedIssuer("usa")
            .setRequireExpirationTime()
            .build();
    SimpleJwtConsumerTestHelp.expectProcessingFailure(jwt, jwtContext, consumer);

    consumer = new JwtConsumerBuilder()
            .setDecryptionKey(encKey.getPrivateKey())
            .setVerificationKey(sigKey.getPublicKey())
            .setEvaluationTime(NumericDate.fromSeconds(1420219088))
            .setExpectedAudience("canada")
            .setDisableRequireSignature()
            .setExpectedIssuer("usa")
            .setRequireExpirationTime()
            .build();
    JwtContext context = consumer.process(jwt);
    JwtClaims jwtClaims = context.getJwtClaims();
    Assert.assertThat("eh", equalTo(jwtClaims.getStringClaimValue("message")));
    consumer.processContext(jwtContext);

}
 
Example #21
Source File: JWTAuthPluginIntegrationTest.java    From lucene-solr with Apache License 2.0 4 votes vote down vote up
@Override
@Before
public void setUp() throws Exception {
  super.setUp();
  
  configureCluster(NUM_SERVERS)// nodes
      .withSecurityJson(TEST_PATH().resolve("security").resolve("jwt_plugin_jwk_security.json"))
      .addConfig("conf1", TEST_PATH().resolve("configsets").resolve("cloud-minimal").resolve("conf"))
      .withDefaultClusterProperty("useLegacyReplicaAssignment", "false")
      .configure();
  baseUrl = cluster.getRandomJetty(random()).getBaseUrl().toString();

  String jwkJSON = "{\n" +
      "  \"kty\": \"RSA\",\n" +
      "  \"d\": \"i6pyv2z3o-MlYytWsOr3IE1olu2RXZBzjPRBNgWAP1TlLNaphHEvH5aHhe_CtBAastgFFMuP29CFhaL3_tGczkvWJkSveZQN2AHWHgRShKgoSVMspkhOt3Ghha4CvpnZ9BnQzVHnaBnHDTTTfVgXz7P1ZNBhQY4URG61DKIF-JSSClyh1xKuMoJX0lILXDYGGcjVTZL_hci4IXPPTpOJHV51-pxuO7WU5M9252UYoiYyCJ56ai8N49aKIMsqhdGuO4aWUwsGIW4oQpjtce5eEojCprYl-9rDhTwLAFoBtjy6LvkqlR2Ae5dKZYpStljBjK8PJrBvWZjXAEMDdQ8PuQ\",\n" +
      "  \"e\": \"AQAB\",\n" +
      "  \"use\": \"sig\",\n" +
      "  \"kid\": \"test\",\n" +
      "  \"alg\": \"RS256\",\n" +
      "  \"n\": \"jeyrvOaZrmKWjyNXt0myAc_pJ1hNt3aRupExJEx1ewPaL9J9HFgSCjMrYxCB1ETO1NDyZ3nSgjZis-jHHDqBxBjRdq_t1E2rkGFaYbxAyKt220Pwgme_SFTB9MXVrFQGkKyjmQeVmOmV6zM3KK8uMdKQJ4aoKmwBcF5Zg7EZdDcKOFgpgva1Jq-FlEsaJ2xrYDYo3KnGcOHIt9_0NQeLsqZbeWYLxYni7uROFncXYV5FhSJCeR4A_rrbwlaCydGxE0ToC_9HNYibUHlkJjqyUhAgORCbNS8JLCJH8NUi5sDdIawK9GTSyvsJXZ-QHqo4cMUuxWV5AJtaRGghuMUfqQ\"\n" +
      "}";

  PublicJsonWebKey jwk = RsaJsonWebKey.Factory.newPublicJwk(jwkJSON);
  JwtClaims claims = JWTAuthPluginTest.generateClaims();
  jws = new JsonWebSignature();
  jws.setPayload(claims.toJson());
  jws.setKey(jwk.getPrivateKey());
  jws.setKeyIdHeaderValue(jwk.getKeyId());
  jws.setAlgorithmHeaderValue(AlgorithmIdentifiers.RSA_USING_SHA256);

  jwtTestToken = jws.getCompactSerialization();
  
  PublicJsonWebKey jwk2 = RsaJwkGenerator.generateJwk(2048);
  jwk2.setKeyId("k2");
  JsonWebSignature jws2 = new JsonWebSignature();
  jws2.setPayload(claims.toJson());
  jws2.setKey(jwk2.getPrivateKey());
  jws2.setKeyIdHeaderValue(jwk2.getKeyId());
  jws2.setAlgorithmHeaderValue(AlgorithmIdentifiers.RSA_USING_SHA256);
  jwtTokenWrongSignature = jws2.getCompactSerialization();

  cluster.waitForAllNodes(10);
}
 
Example #22
Source File: JwtVerifierTest.java    From light-4j with Apache License 2.0 4 votes vote down vote up
@Test
public void testVerifyJwtByJsonWebKeys() throws Exception {
    Map<String, Object> secretConfig = Config.getInstance().getJsonMapConfig(JwtIssuer.SECRET_CONFIG);
    JwtConfig jwtConfig = (JwtConfig) Config.getInstance().getJsonObjectConfig(JwtIssuer.JWT_CONFIG, JwtConfig.class);

    String fileName = jwtConfig.getKey().getFilename();
    String alias = jwtConfig.getKey().getKeyName();

    KeyStore ks = loadKeystore(fileName, (String)secretConfig.get(JwtIssuer.JWT_PRIVATE_KEY_PASSWORD));
    Key privateKey = ks.getKey(alias, ((String) secretConfig.get(JwtIssuer.JWT_PRIVATE_KEY_PASSWORD)).toCharArray());

    JsonWebSignature jws = new JsonWebSignature();

    String iss = "my.test.iss";
    JwtClaims jwtClaims = JwtClaims.parse("{\n" +
            "  \"sub\": \"5745ed4b-0158-45ff-89af-4ce99bc6f4de\",\n" +
            "  \"iss\": \"" + iss  +"\",\n" +
            "  \"subject_type\": \"client-id\",\n" +
            "  \"exp\": 1557419531,\n" +
            "  \"iat\": 1557419231,\n" +
            "  \"scope\": [\n" +
            "    \"my.test.scope.read\",\n" +
            "    \"my.test.scope.write\",\n" +
            "  ],\n" +
            "  \"consumer_application_id\": \"389\",\n" +
            "  \"request_transit\": \"63092\"\n" +
            "}");

    // The payload of the JWS is JSON content of the JWT Claims
    jws.setPayload(jwtClaims.toJson());

    // use private key to sign the JWT
    jws.setKey(privateKey);

    jws.setAlgorithmHeaderValue(AlgorithmIdentifiers.RSA_USING_SHA256);

    String jwt = jws.getCompactSerialization();

    Assert.assertNotNull(jwt);

    System.out.print("JWT = " + jwt);

    JwtVerifier jwtVerifier = new JwtVerifier(Config.getInstance().getJsonMapConfig(CONFIG_NAME));
    JwtClaims claims = jwtVerifier.verifyJwt(jwt, true, true, (kId, isToken) -> {
        try {
            // use public key to create the the JsonWebKey
            Key publicKey = ks.getCertificate(alias).getPublicKey();
            PublicJsonWebKey jwk = PublicJsonWebKey.Factory.newPublicJwk(publicKey);
            List<JsonWebKey> jwkList = Arrays.asList(jwk);
            return new JwksVerificationKeyResolver(jwkList);
        } catch (JoseException | KeyStoreException e) {
            throw new RuntimeException(e);
        }
    });

    Assert.assertNotNull(claims);
    Assert.assertEquals(iss, claims.getStringClaimValue("iss"));
}
 
Example #23
Source File: JwtHelperTest.java    From light-4j with Apache License 2.0 4 votes vote down vote up
@Test
public void testVerifyJwtByJsonWebKeys() throws Exception {
    Map<String, Object> secretConfig = Config.getInstance().getJsonMapConfig(JwtIssuer.SECRET_CONFIG);
    JwtConfig jwtConfig = (JwtConfig) Config.getInstance().getJsonObjectConfig(JwtIssuer.JWT_CONFIG, JwtConfig.class);

    String fileName = jwtConfig.getKey().getFilename();
    String alias = jwtConfig.getKey().getKeyName();

    KeyStore ks = loadKeystore(fileName, (String)secretConfig.get(JwtIssuer.JWT_PRIVATE_KEY_PASSWORD));
    Key privateKey = ks.getKey(alias, ((String) secretConfig.get(JwtIssuer.JWT_PRIVATE_KEY_PASSWORD)).toCharArray());

    JsonWebSignature jws = new JsonWebSignature();

    String iss = "my.test.iss";
    JwtClaims jwtClaims = JwtClaims.parse("{\n" +
            "  \"sub\": \"5745ed4b-0158-45ff-89af-4ce99bc6f4de\",\n" +
            "  \"iss\": \"" + iss  +"\",\n" +
            "  \"subject_type\": \"client-id\",\n" +
            "  \"exp\": 1557419531,\n" +
            "  \"iat\": 1557419231,\n" +
            "  \"scope\": [\n" +
            "    \"my.test.scope.read\",\n" +
            "    \"my.test.scope.write\",\n" +
            "  ],\n" +
            "  \"consumer_application_id\": \"389\",\n" +
            "  \"request_transit\": \"63092\"\n" +
            "}");

    // The payload of the JWS is JSON content of the JWT Claims
    jws.setPayload(jwtClaims.toJson());

    // use private key to sign the JWT
    jws.setKey(privateKey);

    jws.setAlgorithmHeaderValue(AlgorithmIdentifiers.RSA_USING_SHA256);

    String jwt = jws.getCompactSerialization();

    Assert.assertNotNull(jwt);

    System.out.print("JWT = " + jwt);

    JwtClaims claims = JwtHelper.verifyJwt(jwt, true, true, (kId, isToken) -> {
        try {
            // use public key to create the the JsonWebKey
            Key publicKey = ks.getCertificate(alias).getPublicKey();
            PublicJsonWebKey jwk = PublicJsonWebKey.Factory.newPublicJwk(publicKey);
            List<JsonWebKey> jwkList = Arrays.asList(jwk);
            return new JwksVerificationKeyResolver(jwkList);
        } catch (JoseException | KeyStoreException e) {
            throw new RuntimeException(e);
        }
    });

    Assert.assertNotNull(claims);
    Assert.assertEquals(iss, claims.getStringClaimValue("iss"));
}
 
Example #24
Source File: JwtConsumerTest.java    From Jose4j with Apache License 2.0 4 votes vote down vote up
@Test
public void ctyValueVariationsInNested() throws Exception
{
    // Nested jwt with variations on "cty":"JWT" like jwt, application/jwt, application/JWT ...

    PublicJsonWebKey sigKey = PublicJsonWebKey.Factory.newPublicJwk("{\"kty\":\"EC\",\"x\":\"HVDkXtG_j_JQUm_mNaRPSbsEhr6gdK0a6H4EURypTU0\",\"y\":\"NxdYFS2hl1w8VKf5UTpGXh2YR7KQ8gSBIHu64W0mK8M\",\"crv\":\"P-256\",\"d\":\"ToqTlgJLhI7AQYNLesI2i-08JuaYm2wxTCDiF-VxY4A\"}");
    PublicJsonWebKey encKey = PublicJsonWebKey.Factory.newPublicJwk("{\"kty\":\"EC\",\"x\":\"7kaETHB4U9pCdsErbjw11HGv8xcQUmFy3NMuBa_J7Os\",\"y\":\"FZK-vSMpKk9gLWC5wdFjG1W_C7vgJtdm1YfNPZevmCw\",\"crv\":\"P-256\",\"d\":\"spOxtF0qiKrrCTaUs_G04RISjCx7HEgje_I7aihXVMY\"}");

    String jwt;
    jwt = "eyJ6aXAiOiJERUYiLCJhbGciOiJFQ0RILUVTIiwiZW5jIjoiQTEyOENCQy1IUzI1NiIsImN0eSI6ImFwcGxpY2F0aW9uL2p3dCIsImVwayI6eyJrdHkiOiJFQyIsIngiOiJCOUhPbG82UV9LV0NiQjZLbk1RMDFfaHcyRXdaQWNEMmNucEdYYVl5WFBBIiwieSI6InJYS2s3VzM4UXhVOHl4YWZZc3NsUjFWU2JLbDI5T0FNSWxROFBCWXVZcUEiLCJjcnYiOiJQLTI1NiJ9fQ..LcIG9_bnPb43aaps32H6yQ.rsV7ItJWWfNafDJmeLHluKhiwmsU0Mlwut2jwD6y96KpjD-hz_5zBxpXtj6mk8yGZwg2L26XLo8npt_82bhKnMYqlKSRM-3ge2Deg5WPmBCx6Fj0NyCMnoR8oJTn-oxh0OHZICK_85Xz3GptopeA3Hj8ESdsJEI6D4WbXQ7HfGeg8ID9uvTaL8NGOHT4BGY0bB-6nl3qNIY5ULpg-a4a1ou5k9HnM6SRSpVRwpBBUsk.1vqvwv9XAzsQfvragyMXZQ";
    JwtConsumer firstPassConsumer = new JwtConsumerBuilder()
            .setDecryptionKey(encKey.getPrivateKey())
            .setSkipAllValidators()
            .setDisableRequireSignature()
            .setSkipSignatureVerification()
            .setEnableLiberalContentTypeHandling()
            .build();
    JwtContext jwtContext = firstPassConsumer.process(jwt);
    Assert.assertThat("eh", equalTo(jwtContext.getJwtClaims().getStringClaimValue("message")));
    JwtConsumer consumer = new JwtConsumerBuilder()
            .setDecryptionKey(encKey.getPrivateKey())
            .setVerificationKey(sigKey.getPublicKey())
            .setEvaluationTime(NumericDate.fromSeconds(1420219088))
            .setExpectedAudience("canada")
            .setExpectedIssuer("usa")
            .setRequireExpirationTime()
            .build();
    JwtContext context = consumer.process(jwt);
    JwtClaims jwtClaims = context.getJwtClaims();
    Assert.assertThat("eh", equalTo(jwtClaims.getStringClaimValue("message")));
    consumer.processContext(jwtContext);

    jwt = "eyJ6aXAiOiJERUYiLCJhbGciOiJFQ0RILUVTIiwiZW5jIjoiQTEyOENCQy1IUzI1NiIsImN0eSI6ImFwcGxpY2F0aW9uL0pXVCIsImVwayI6eyJrdHkiOiJFQyIsIngiOiJxelBlRUl0ZXJmQ0dhTFBpbDU3UmRudERHQVdwdVlBRGtVLUJubkkyTXowIiwieSI6ImNmWUxlc1dneGlfVndCdzdvSzNPT3dabGNrbVRCVmMzcEdnMTNRZ3V5WjQiLCJjcnYiOiJQLTI1NiJ9fQ..ftNMf4CqUSCq8p3L1Y7K1A.Z9K1YIJmSY9du5LUuSs0szCj1PUzq0ZnsEppT8yVPdGVDkDi0elEcsM8dCq8CvYrXG8OFuyp0s8dd2u_fIw4RjMc-aVMBT4ikWDmqb4CA17nC2Hxm6dZFPy3Xx3GnqjiGUIB2JiMOxj6mBZtTSvkKAUvs3Rh4G-87v2hJFpqdLSySqd-rQXL7Dhqxl0Cbu9nZFcYEIk58lpC0H2TN9aP5GtuQYa3BlNuEoEDzIcLhc4.N6VFQ0_UgNqyBsPLyE6MQQ";
    firstPassConsumer = new JwtConsumerBuilder()
            .setDecryptionKey(encKey.getPrivateKey())
            .setSkipAllValidators()
            .setDisableRequireSignature()
            .setSkipSignatureVerification()
            .setEnableLiberalContentTypeHandling()
            .build();
    jwtContext = firstPassConsumer.process(jwt);
    Assert.assertThat("eh", equalTo(jwtContext.getJwtClaims().getStringClaimValue("message")));
    consumer = new JwtConsumerBuilder()
            .setDecryptionKey(encKey.getPrivateKey())
            .setVerificationKey(sigKey.getPublicKey())
            .setEvaluationTime(NumericDate.fromSeconds(1420219095))
            .setExpectedAudience("canada")
            .setExpectedIssuer("usa")
            .setRequireExpirationTime()
            .build();
    context = consumer.process(jwt);
    jwtClaims = context.getJwtClaims();
    Assert.assertThat("eh", equalTo(jwtClaims.getStringClaimValue("message")));
    consumer.processContext(jwtContext);


    jwt = "eyJ6aXAiOiJERUYiLCJhbGciOiJFQ0RILUVTIiwiZW5jIjoiQTEyOENCQy1IUzI1NiIsImN0eSI6Imp3dCIsImVwayI6eyJrdHkiOiJFQyIsIngiOiJoTm5zTlRXZWN3TEVRUGVRMlFjZ05WSDJLX0dzTkFUZXNVaENhY2x2OVAwIiwieSI6ImI2V1lSR1V5Z1NBUGo5a0lFYktYTm5ZaDhEbmNrRXB2NDFYbUVnanA4VE0iLCJjcnYiOiJQLTI1NiJ9fQ..VGTURmPYERdJ7q9_5wlENA.91m_JN65XNlp9WsFHaHihhGB7soKNUdeBNpmODVcIiinhPClH00-GTMwfT08VmXEU2djW3Aw_eBAoU7rI_M0ovYbbmAy7UnVRUyCTbkGsQpv7OxYIznemMVMraFuHNmTAF_MU7oM4gPkqKzwuBa0uwd4JhN00bq-jEcLifMPgMvyGvfJ19SXAyrIVA4Otjuii347V5u1GwlB5VBqMiqtBnbMMzR1Fe3X-4-sEgT9BrM.4T3uLGa4Bm5_r-ZNKPzEWg";
    firstPassConsumer = new JwtConsumerBuilder()
            .setDecryptionKey(encKey.getPrivateKey())
            .setSkipAllValidators()
            .setDisableRequireSignature()
            .setSkipSignatureVerification()
            .setEnableLiberalContentTypeHandling()
            .build();
    jwtContext = firstPassConsumer.process(jwt);
    Assert.assertThat("eh", equalTo(jwtContext.getJwtClaims().getStringClaimValue("message")));
    consumer = new JwtConsumerBuilder()
            .setDecryptionKey(encKey.getPrivateKey())
            .setVerificationKey(sigKey.getPublicKey())
            .setEvaluationTime(NumericDate.fromSeconds(1420219099))
            .setExpectedAudience("canada")
            .setExpectedIssuer("usa")
            .setRequireExpirationTime()
            .build();
    context = consumer.process(jwt);
    jwtClaims = context.getJwtClaims();
    Assert.assertThat("eh", equalTo(jwtClaims.getStringClaimValue("message")));
    consumer.processContext(jwtContext);

    jwt = "eyJ6aXAiOiJERUYiLCJhbGciOiJFQ0RILUVTIiwiZW5jIjoiQTEyOENCQy1IUzI1NiIsImN0eSI6ImpXdCIsImVwayI6eyJrdHkiOiJFQyIsIngiOiJmYTlJVEh6cEROSG1uV2NDSDVvWGtFYjJ1SncwTXNOU2stQjdFb091WUEwIiwieSI6IkZ1U0RaVXdmb1EtQXB6dEFQRUc1dk40QmZRR2sxWnRMT0FzM1o0a19obmciLCJjcnYiOiJQLTI1NiJ9fQ..FmuORwLWIoNBbRh0XcBzJQ.pSr58DMuRstF3A6xj24yM4KvNgWxtb_QDKuldesTCD-R00BNFwIVx4F51VL5DwR54ITgBZBKdAT4pN6eM-td5VrWBCnSWxFjNrBoDnnRkDfFgq8OjOBaR7k_4zUk41bBikDZ0JOQDWuiaODYBk7PWq0mgotvLPbJ9oc7zfp6lbHqaYXjbzfuD56W_kDYO8zSjiZUGLcYgJDYnO3F8K-QhP02v-0OEpAGrm5SKKV3Txk.Ecojfru8KbkqIw4QvYS3qA";
    firstPassConsumer = new JwtConsumerBuilder()
            .setDecryptionKey(encKey.getPrivateKey())
            .setSkipAllValidators()
            .setDisableRequireSignature()
            .setSkipSignatureVerification()
            .setEnableLiberalContentTypeHandling()
            .build();
    jwtContext = firstPassConsumer.process(jwt);
    consumer = new JwtConsumerBuilder()
            .setDecryptionKey(encKey.getPrivateKey())
            .setVerificationKey(sigKey.getPublicKey())
            .setEvaluationTime(NumericDate.fromSeconds(1420220122))
            .setExpectedAudience("canada")
            .setExpectedIssuer("usa")
            .setRequireExpirationTime()
            .build();
    context = consumer.process(jwt);
    jwtClaims = context.getJwtClaims();
    Assert.assertThat("eh", equalTo(jwtClaims.getStringClaimValue("message")));
    consumer.processContext(jwtContext);
}
 
Example #25
Source File: EcdhKeyAgreementAlgorithmTest.java    From Jose4j with Apache License 2.0 4 votes vote down vote up
public void testExampleJwaAppendixC() throws JoseException
{
    // testing http://tools.ietf.org/html/draft-ietf-jose-json-web-algorithms-17#appendix-D
    // now http://tools.ietf.org/html/draft-ietf-jose-json-web-algorithms-26#appendix-C
    String receiverJwkJson = "\n{\"kty\":\"EC\",\n" +
            " \"crv\":\"P-256\",\n" +
            " \"x\":\"weNJy2HscCSM6AEDTDg04biOvhFhyyWvOHQfeF_PxMQ\",\n" +
            " \"y\":\"e8lnCO-AlStT-NJVX-crhB7QRYhiix03illJOVAOyck\",\n" +
            " \"d\":\"VEmDZpDXXK8p8N0Cndsxs924q6nS1RXFASRl6BfUqdw\"\n" +
            "}";
    PublicJsonWebKey receiverJwk = PublicJsonWebKey.Factory.newPublicJwk(receiverJwkJson);

    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);

    Headers headers = new Headers();

    headers.setStringHeaderValue(HeaderParameterNames.ALGORITHM, KeyManagementAlgorithmIdentifiers.ECDH_ES);
    headers.setStringHeaderValue(HeaderParameterNames.ENCRYPTION_METHOD, ContentEncryptionAlgorithmIdentifiers.AES_128_GCM);

    headers.setStringHeaderValue(HeaderParameterNames.AGREEMENT_PARTY_U_INFO, "QWxpY2U");
    headers.setStringHeaderValue(HeaderParameterNames.AGREEMENT_PARTY_V_INFO, "Qm9i");

    headers.setJwkHeaderValue(HeaderParameterNames.EPHEMERAL_PUBLIC_KEY, ephemeralJwk);

    EcdhKeyAgreementAlgorithm ecdhKeyAgreementAlgorithm = new EcdhKeyAgreementAlgorithm();

    ContentEncryptionKeyDescriptor cekDesc = new ContentEncryptionKeyDescriptor(ByteUtil.byteLength(128), AesKey.ALGORITHM);

    PublicKey pubKey = receiverJwk.getPublicKey();
    ContentEncryptionKeys contentEncryptionKeys = ecdhKeyAgreementAlgorithm.manageForEncrypt(pubKey, cekDesc, headers, ephemeralJwk, ProviderContextTest.EMPTY_CONTEXT);

    assertTrue(contentEncryptionKeys.getEncryptedKey().length == 0);
    Base64Url base64Url = new Base64Url();
    assertEquals("VqqN6vgjbSBcIijNcacQGg", base64Url.base64UrlEncode(contentEncryptionKeys.getContentEncryptionKey()));

    Headers receivedHeaders = new Headers();
    receivedHeaders.setFullHeaderAsJsonString(headers.getFullHeaderAsJsonString());

    Key key = ecdhKeyAgreementAlgorithm.manageForDecrypt(receiverJwk.getPrivateKey(), null, cekDesc, receivedHeaders, ProviderContextTest.EMPTY_CONTEXT);
    assertEquals("VqqN6vgjbSBcIijNcacQGg", base64Url.base64UrlEncode(key.getEncoded()));
}
 
Example #26
Source File: EcdhKeyAgreementAlgorithmTest.java    From Jose4j with Apache License 2.0 4 votes vote down vote up
public void testDV256() throws JoseException
    {
    /*
        A working test w/ data produced by Dmitry Vsekhvalnov doing ECDH with P-256 + ConcatKDF to produce a 256 bit key
        ---
        Ok, data below. Everything base64url encoded. partyUInfo=partyVInfo=[0,0,0,0] in all samples.

        Curve P-256, 256 bit key (match to jose4j and to spec sample, provided as reference)

        X = BHId3zoDv6pDgOUh8rKdloUZ0YumRTcaVDCppUPoYgk
        Y = g3QIDhaWEksYtZ9OWjNHn9a6-i_P9o5_NrdISP0VWDU
        D = KpTnMOHEpskXvuXHFCfiRtGUHUZ9Dq5CCcZQ-19rYs4

        ephemeral X = UWlKW_GHsZa1ikOUPocsMi2pNh_1K2vhn6ZjJqALOK8
        ephemeral Y = n2oj0Z6EYgzRDmeROILD4fp2zAMGLQzmI8G1k5nsev0

        algId = AAAADUExMjhDQkMtSFMyNTY
        suppPubInfo = AAABAA

        derived key = bqXVMd1yd5E08Wy2T1U9m9Q5DEjj7-BYIyWUgazzZkA
     */

    String receiverJwkJson = "\n{\"kty\":\"EC\",\n" +
            " \"crv\":\"P-256\",\n" +
            " \"x\":\"BHId3zoDv6pDgOUh8rKdloUZ0YumRTcaVDCppUPoYgk\",\n" +
            " \"y\":\"g3QIDhaWEksYtZ9OWjNHn9a6-i_P9o5_NrdISP0VWDU\",\n" +
            " \"d\":\"KpTnMOHEpskXvuXHFCfiRtGUHUZ9Dq5CCcZQ-19rYs4\"\n" +
            "}";
    PublicJsonWebKey receiverJwk = PublicJsonWebKey.Factory.newPublicJwk(receiverJwkJson);

    String ephemeralJwkJson = "\n{\"kty\":\"EC\",\n" +
            " \"crv\":\"P-256\",\n" +
            " \"x\":\"UWlKW_GHsZa1ikOUPocsMi2pNh_1K2vhn6ZjJqALOK8\",\n" +
            " \"y\":\"n2oj0Z6EYgzRDmeROILD4fp2zAMGLQzmI8G1k5nsev0\"\n" +
            "}";

    PublicJsonWebKey ephemeralJwk = PublicJsonWebKey.Factory.newPublicJwk(ephemeralJwkJson);

    Headers headers = new Headers();

    headers.setStringHeaderValue(HeaderParameterNames.ALGORITHM, KeyManagementAlgorithmIdentifiers.ECDH_ES);
    headers.setStringHeaderValue(HeaderParameterNames.ENCRYPTION_METHOD, ContentEncryptionAlgorithmIdentifiers.AES_128_CBC_HMAC_SHA_256);

    headers.setJwkHeaderValue(HeaderParameterNames.EPHEMERAL_PUBLIC_KEY, ephemeralJwk);

    EcdhKeyAgreementAlgorithm ecdhKeyAgreementAlgorithm = new EcdhKeyAgreementAlgorithm();

    ContentEncryptionKeyDescriptor cekDesc = new ContentEncryptionKeyDescriptor(ByteUtil.byteLength(256), AesKey.ALGORITHM);

    Key derivedKey = ecdhKeyAgreementAlgorithm.manageForDecrypt(receiverJwk.getPrivateKey(), null, cekDesc, headers, ProviderContextTest.EMPTY_CONTEXT);
    assertEquals("bqXVMd1yd5E08Wy2T1U9m9Q5DEjj7-BYIyWUgazzZkA", Base64Url.encode(derivedKey.getEncoded()));
}
 
Example #27
Source File: DecryptPioneerPayloadsTest.java    From gcp-ingestion with Mozilla Public License 2.0 4 votes vote down vote up
/** Load a private key from a JWK. See the KeyStore for more details. */
private PrivateKey loadPrivateKey(String resourceLocation) throws Exception {
  byte[] data = Resources.toByteArray(Resources.getResource(resourceLocation));
  PublicJsonWebKey key = PublicJsonWebKey.Factory.newPublicJwk(new String(data));
  return key.getPrivateKey();
}
 
Example #28
Source File: JwtConsumerTest.java    From Jose4j with Apache License 2.0 4 votes vote down vote up
@Test
public void missingCtyInNested() throws Exception
{
    // Nested jwt without "cty":"JWT" -> expect failure here as the cty is a MUST for nesting
    // setEnableLiberalContentTypeHandling() on the builder will enable a best effort to deal with the content even when cty isn't specified

    String jwt = "eyJ6aXAiOiJERUYiLCJhbGciOiJFQ0RILUVTIiwiZW5jIjoiQTEyOENCQy1IUzI1NiIsImVwayI6eyJrdHkiOiJFQyIsIngiOiIwRGk0VTBZQ0R2NHAtS2hETUZwUThvY0FsZzA2SEwzSHR6UldRbzlDLWV3IiwieSI6IjBfVFJjR1Y3Qy05d0xseFJZSExJOFlKTXlET2hWNW5YeHVPMGdRVmVxd0EiLCJjcnYiOiJQLTI1NiJ9fQ..xw5H8Kztd_sqzbXjt4GKUg.YNa163HLj7MwlvjzGihbOHnJ2PC3NOTnnvVOanuk1O9XFJ97pbbHHQzEeEwG6jfvDgdmlrLjcIJkSu1U8qRby7Xr4gzP6CkaDPbKwvLveETZSNdmZh37XKfnQ4LvKgiko6OQzyLYG1gc97kUOeikXTYVaYaeV1838Bi4q3DsIG-j4ZESg0-ePQesw56A80AEE3j6wXwZ4vqugPP9_ogZzkPFcHf1lt3-A4amNMjDbV8.u-JJCoakXI55BG2rz_kBlg";
    PublicJsonWebKey sigKey = PublicJsonWebKey.Factory.newPublicJwk("{\"kty\":\"EC\",\"x\":\"loF6m9WAW_GKrhoh48ctg_d78fbIsmUb02XDOwJj59c\",\"y\":\"kDCHDkCbWjeX8DjD9feQKcndJyerdsLJ4VZ5YSTWCoU\",\"crv\":\"P-256\",\"d\":\"6D1C9gJsT9KXNtTNyqgpdyQuIrK-qzo0_QJOVe9DqJg\"}");
    PublicJsonWebKey encKey = PublicJsonWebKey.Factory.newPublicJwk("{\"kty\":\"EC\",\"x\":\"PNbMydlpYRBFTYn_XDFvvRAFqE4e0EJmK6-zULTVERs\",\"y\":\"dyO9wGVgKS3gtP5bx0PE8__MOV_HLSpiwK-mP1RGZgk\",\"crv\":\"P-256\",\"d\":\"FIs8wVojHBdl7vkiZVnLBPw5S9lbn4JF2WWY1OTupic\"}");

    JwtConsumer firstPassConsumer = new JwtConsumerBuilder()
            .setDecryptionKey(encKey.getPrivateKey())
            .setSkipAllValidators()
            .setDisableRequireSignature()
            .setSkipSignatureVerification()
            .setEnableLiberalContentTypeHandling()
            .build();

    JwtContext jwtContext = firstPassConsumer.process(jwt);

    JwtConsumer consumer = new JwtConsumerBuilder()
            .setDecryptionKey(encKey.getPrivateKey())
            .setVerificationKey(sigKey.getPublicKey())
            .setEvaluationTime(NumericDate.fromSeconds(1420219088))
            .setExpectedAudience("canada")
            .setExpectedIssuer("usa")
            .setRequireExpirationTime()
            .build();
    SimpleJwtConsumerTestHelp.expectProcessingFailure(jwt, consumer);

    consumer = new JwtConsumerBuilder()
            .setEnableLiberalContentTypeHandling()
            .setDecryptionKey(encKey.getPrivateKey())
            .setVerificationKey(sigKey.getPublicKey())
            .setEvaluationTime(NumericDate.fromSeconds(1420219088))
            .setExpectedAudience("canada")
            .setExpectedIssuer("usa")
            .setRequireExpirationTime()
            .build();
    JwtContext ctx = consumer.process(jwt);
    consumer.processContext(jwtContext);

    for (JwtContext context : new JwtContext[] {ctx, jwtContext})
    {
        JwtClaims jwtClaims = context.getJwtClaims();
        Assert.assertThat("eh", equalTo(jwtClaims.getStringClaimValue("message")));
        List<JsonWebStructure> joseObjects = context.getJoseObjects();
        assertThat(2, equalTo(joseObjects.size()));
        assertTrue(joseObjects.get(0) instanceof JsonWebSignature);
        assertTrue(joseObjects.get(1) instanceof JsonWebEncryption);
    }
}
 
Example #29
Source File: DecryptAetIdentifiersTest.java    From gcp-ingestion with Mozilla Public License 2.0 4 votes vote down vote up
/** Load a public key from a JWK. See the KeyStore for more details. */
private static PublicJsonWebKey loadPublicKey(String resourceLocation) throws Exception {
  byte[] data = Resources.toByteArray(Resources.getResource(resourceLocation));
  return PublicJsonWebKey.Factory.newPublicJwk(new String(data));
}
 
Example #30
Source File: X509UtilTest.java    From Jose4j with Apache License 2.0 4 votes vote down vote up
public void testFromBase64DerAndBackAndMore() throws JoseException
{
    String s =
            "MIICUTCCAfugAwIBAgIBADANBgkqhkiG9w0BAQQFADBXMQswCQYDVQQGEwJDTjEL\n" +
            "MAkGA1UECBMCUE4xCzAJBgNVBAcTAkNOMQswCQYDVQQKEwJPTjELMAkGA1UECxMC\n" +
            "VU4xFDASBgNVBAMTC0hlcm9uZyBZYW5nMB4XDTA1MDcxNTIxMTk0N1oXDTA1MDgx\n" +
            "NDIxMTk0N1owVzELMAkGA1UEBhMCQ04xCzAJBgNVBAgTAlBOMQswCQYDVQQHEwJD\n" +
            "TjELMAkGA1UEChMCT04xCzAJBgNVBAsTAlVOMRQwEgYDVQQDEwtIZXJvbmcgWWFu\n" +
            "ZzBcMA0GCSqGSIb3DQEBAQUAA0sAMEgCQQCp5hnG7ogBhtlynpOS21cBewKE/B7j\n" +
            "V14qeyslnr26xZUsSVko36ZnhiaO/zbMOoRcKK9vEcgMtcLFuQTWDl3RAgMBAAGj\n" +
            "gbEwga4wHQYDVR0OBBYEFFXI70krXeQDxZgbaCQoR4jUDncEMH8GA1UdIwR4MHaA\n" +
            "FFXI70krXeQDxZgbaCQoR4jUDncEoVukWTBXMQswCQYDVQQGEwJDTjELMAkGA1UE\n" +
            "CBMCUE4xCzAJBgNVBAcTAkNOMQswCQYDVQQKEwJPTjELMAkGA1UECxMCVU4xFDAS\n" +
            "BgNVBAMTC0hlcm9uZyBZYW5nggEAMAwGA1UdEwQFMAMBAf8wDQYJKoZIhvcNAQEE\n" +
            "BQADQQA/ugzBrjjK9jcWnDVfGHlk3icNRq0oV7Ri32z/+HQX67aRfgZu7KWdI+Ju\n" +
            "Wm7DCfrPNGVwFWUQOmsPue9rZBgO\n";

    X509Util x5u = new X509Util();
    X509Certificate x509Certificate = x5u.fromBase64Der(s);
    assertTrue(x509Certificate.getSubjectDN().toString().contains("Yang"));

    String pem = x5u.toPem(x509Certificate);
    assertTrue(pem.charAt(BaseNCodec.PEM_CHUNK_SIZE) == '\r');
    assertTrue(pem.charAt(BaseNCodec.PEM_CHUNK_SIZE + 1) == '\n');

    String encoded = x5u.toBase64(x509Certificate);
    assertEquals(-1, encoded.indexOf('\r'));
    assertEquals(-1, encoded.indexOf('\n'));

    PublicJsonWebKey jwk = PublicJsonWebKey.Factory.newPublicJwk(x509Certificate.getPublicKey());
    jwk.setCertificateChain(x509Certificate);
    String jsonJwk = jwk.toJson(JsonWebKey.OutputControlLevel.PUBLIC_ONLY);

    Map<String,Object> parsed = JsonUtil.parseJson(jsonJwk);
    List<String> x5cStrings = (List<String>) parsed.get(PublicJsonWebKey.X509_CERTIFICATE_CHAIN_PARAMETER);
    String  x5cValue = x5cStrings.get(0);
    assertEquals(-1, x5cValue.indexOf('\r'));
    assertEquals(-1, x5cValue.indexOf('\n'));

    PublicJsonWebKey jwkFromJson = PublicJsonWebKey.Factory.newPublicJwk(jsonJwk);
    assertEquals(x509Certificate.getPublicKey(), jwkFromJson.getPublicKey());
    assertEquals(x509Certificate, jwkFromJson.getLeafCertificate());
}