org.jose4j.lang.JoseException Java Examples

The following examples show how to use org.jose4j.lang.JoseException. 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: HttpsJwks.java    From Jose4j with Apache License 2.0 6 votes vote down vote up
public void refresh() throws JoseException, IOException
{
    log.debug("Refreshing/loading JWKS from {}", location);
    SimpleResponse simpleResponse = simpleHttpGet.get(location);
    JsonWebKeySet jwks = new JsonWebKeySet(simpleResponse.getBody());
    List<JsonWebKey> keys = jwks.getJsonWebKeys();
    long cacheLife = getCacheLife(simpleResponse);
    if (cacheLife <= 0)
    {
        log.debug("Will use default cache duration of {} seconds for content from {}", defaultCacheDuration, location);
        cacheLife = defaultCacheDuration;
    }
    long exp = System.currentTimeMillis() + (cacheLife * 1000L);
    log.debug("Updated JWKS content from {} will be cached for {} seconds until {} -> {}", location, cacheLife, new Date(exp), keys);
    cache = new Cache(keys, exp);
}
 
Example #2
Source File: DecryptAetIdentifiers.java    From gcp-ingestion with Mozilla Public License 2.0 6 votes vote down vote up
/**
 * Decrypt a payload encoded in a compact serialization of JSON Web Encryption (JWE).
 *
 * <p>The payload may be either a single JWE string or an array of values.
 *
 * <p>Assumes that the payload contains a "kid" parameter that can be used to look up a matching
 * private key.
 */
public static JsonNode decrypt(KeyStore keyStore, JsonNode anonIdNode)
    throws JoseException, KeyNotFoundException {
  if (anonIdNode.isTextual()) {
    String anonId = anonIdNode.textValue();
    JsonWebStructure fromCompact = JsonWebEncryption.fromCompactSerialization(anonId);
    String keyId = fromCompact.getKeyIdHeaderValue();
    PrivateKey key = keyStore.getKeyOrThrow(keyId);
    JsonWebEncryption jwe = new JsonWebEncryption();
    jwe.setKey(key);
    jwe.setContentEncryptionKey(key.getEncoded());
    jwe.setCompactSerialization(anonId);
    return TextNode.valueOf(jwe.getPlaintextString());
  } else if (anonIdNode.isArray()) {
    ArrayNode userIds = Json.createArrayNode();
    for (JsonNode node : anonIdNode) {
      userIds.add(decrypt(keyStore, node));
    }
    return userIds;
  } else {
    throw new IllegalArgumentException(
        "Argument to decrypt must be a TextNode or ArrayNode, but got " + anonIdNode);
  }
}
 
Example #3
Source File: EcKeyUtil.java    From Jose4j with Apache License 2.0 6 votes vote down vote up
public KeyPair generateKeyPair(ECParameterSpec spec) throws JoseException
{
    KeyPairGenerator keyGenerator = getKeyPairGenerator();

    try
    {
        if (secureRandom == null)
        {
            keyGenerator.initialize(spec);
        }
        else
        {
            keyGenerator.initialize(spec, secureRandom);
        }
        return keyGenerator.generateKeyPair();
    }
    catch (InvalidAlgorithmParameterException e)
    {
        throw new JoseException("Unable to create EC key pair with spec " + spec, e);
    }
}
 
Example #4
Source File: SimpleAeadCipher.java    From Jose4j with Apache License 2.0 6 votes vote down vote up
public CipherOutput encrypt(Key key, byte[] iv, byte[] plaintext, byte[] aad, String provider) throws JoseException
{
    Cipher cipher = getInitialisedCipher(key, iv, Cipher.ENCRYPT_MODE, provider);
    updateAad(cipher, aad);

    byte[] cipherOutput;
    try
    {
        cipherOutput = cipher.doFinal(plaintext);
    }
    catch (IllegalBlockSizeException | BadPaddingException e)
    {
        throw new JoseException(e.toString(), e);
    }

    CipherOutput result = new CipherOutput();
    int tagIndex = cipherOutput.length - tagByteLength;
    result.ciphertext = ByteUtil.subArray(cipherOutput, 0, tagIndex);
    result.tag = ByteUtil.subArray(cipherOutput, tagIndex, tagByteLength);
    return result;
}
 
Example #5
Source File: EllipticCurveJsonWebKeyTest.java    From Jose4j with Apache License 2.0 6 votes vote down vote up
@Test
public void testFromKeyWithPrivate512() throws JoseException
{
    PublicJsonWebKey jwk = PublicJsonWebKey.Factory.newPublicJwk(ExampleEcKeysFromJws.PUBLIC_521);
    assertEquals(EllipticCurves.P_521, ((EllipticCurveJsonWebKey)jwk).getCurveName());
    String jsonNoPrivateKey = jwk.toJson();
    jwk.setPrivateKey(ExampleEcKeysFromJws.PRIVATE_521);
    String d = "AY5pb7A0UFiB3RELSD64fTLOSV_jazdF7fLYyuTw8lOfRhWg6Y6rUrPAxerEzgdRhajnu0ferB0d53vM9mE15j2C";
    assertFalse(jwk.toJson().contains(d));
    assertEquals(jsonNoPrivateKey, jwk.toJson());

    assertFalse(jwk.toJson(PUBLIC_ONLY).contains(d));
    assertFalse(jwk.toJson().contains(d));
    assertFalse(jwk.toJson(INCLUDE_SYMMETRIC).contains(d));
    assertTrue(jwk.toJson(INCLUDE_PRIVATE).contains(d));

    System.out.println(jwk);
}
 
Example #6
Source File: Pbkdf2JwkExampleTest.java    From Jose4j with Apache License 2.0 6 votes vote down vote up
@Test
public void testThePbdkfPartFromJwkAppendixC() throws IOException, JoseException
{
    // just the pbkdf2 part from http://tools.ietf.org/html/draft-ietf-jose-json-web-key-22#appendix-C

    String pass = "Thus from my lips, by yours, my sin is purged.";

    // The Salt value (UTF8(Alg) || 0x00 || Salt Input) is:
    byte[] saltValue = ByteUtil.convertUnsignedToSignedTwosComp(new int[]{80, 66, 69, 83, 50, 45, 72, 83, 50, 53, 54, 43, 65, 49, 50, 56, 75,
            87, 0, 217, 96, 147, 112, 150, 117, 70, 247, 127, 8, 155, 137, 174,
            42, 80, 215});

    int iterationCount = 4096;

    PasswordBasedKeyDerivationFunction2 pbkdf2 = new PasswordBasedKeyDerivationFunction2(MacUtil.HMAC_SHA256);
    byte[] derived = pbkdf2.derive(StringUtil.getBytesUtf8(pass), saltValue, iterationCount, 16);
    byte[] expectedDerived = ByteUtil.convertUnsignedToSignedTwosComp(new int[]{110, 171, 169, 92, 129, 92, 109, 117, 233, 242, 116, 233, 170, 14, 24, 75});
    Assert.assertArrayEquals(expectedDerived, derived);
}
 
Example #7
Source File: JsonWebStructureTest.java    From Jose4j with Apache License 2.0 6 votes vote down vote up
@Test
public void jwe2() throws JoseException
{
    String cs = "eyJhbGciOiJBMjU2S1ciLCJlbmMiOiJBMTI4Q0JDLUhTMjU2Iiwia2lkIjoiOWVyIn0." +
            "RAqGCBMFk7O-B-glFckcFmxUr8BTTXuZk-bXAdRZxpk5Vgs_1yoUQw." +
            "hyl68_ADlK4VRDYiQMQS6w." +
            "xk--JKIVF4Xjxc0gRGPL30s4PSNtj685WYqXbjyItG0uSffD4ajGXdz4BO8i0sbM." +
            "WXaAVpBgftXyO1HkkRvgQQ";
    JsonWebStructure jwx = JsonWebStructure.fromCompactSerialization(cs);
    jwx.setKey(oct256bitJwk.getKey());
    Assert.assertTrue(cs + " should give a JWE " + jwx, jwx instanceof JsonWebEncryption);
    Assert.assertEquals(KeyManagementAlgorithmIdentifiers.A256KW, jwx.getAlgorithmHeaderValue());
    Assert.assertEquals(oct256bitJwk.getKeyId(), jwx.getKeyIdHeaderValue());
    String payload = jwx.getPayload();
    Assert.assertEquals(YOU_LL_GET_NOTHING_AND_LIKE_IT, payload);
}
 
Example #8
Source File: JoseCookbookTest.java    From Jose4j with Apache License 2.0 6 votes vote down vote up
private EllipticCurveJsonWebKey commonEcKey(String jwkJson) throws JoseException
{
    JsonWebKey jwk = JsonWebKey.Factory.newJwk(jwkJson);
    assertThat(jwk.getKeyId(), is(equalTo("[email protected]")));
    assertThat(jwk.getUse(), is(equalTo(Use.SIGNATURE)));
    EllipticCurveJsonWebKey ecJwk = (EllipticCurveJsonWebKey) jwk;
    String curveName = ecJwk.getCurveName();
    assertThat(curveName, is(equalTo(EllipticCurves.P_521)));

    Key key = jwk.getKey();
    JsonWebKey jwkFromKey = JsonWebKey.Factory.newJwk(key);
    String jsonOutput = jwkFromKey.toJson(JsonWebKey.OutputControlLevel.PUBLIC_ONLY);
    // check the x and y in the output look the same (to ensure leading zero bytes are there, for example)
    assertThat(jsonOutput, containsString("\"AHKZLLOsCOzz5cY97ewNUajB957y-C-U88c3v13nmGZx6sYl_oJXu9A5RkTKqjqvjyekWF-7ytDyRXYgCF5cj0Kt\""));
    assertThat(jsonOutput, containsString("\"AdymlHvOiLxXkEhayXQnNCvDX4h9htZaCJN34kfmC6pV5OhQHiraVySsUdaQkAgDPrwQrJmbnX9cwlGfP-HqHZR1\""));
    // make sure the private key isn't there
    assertThat(jsonOutput, not(containsString("AAhRON2r9cqXX1hg-RoI6R1tX5p2rUAYdmpHZoC1XNM56KtscrX6zbKipQrCW9CGZH3T4ubpnoTKLDYJ_fF3_rJt")));
    return ecJwk;
}
 
Example #9
Source File: EcdsaUsingShaTest.java    From Jose4j with Apache License 2.0 6 votes vote down vote up
public void testBadKeys() throws JoseException
{
    String cs256 = "eyJhbGciOiJFUzI1NiJ9.UEFZTE9BRCEhIQ.WcL6cqkJSkzwK4Y85Lj96l-_WVmII6foW8d7CJNgdgDxi6NnTdXQD1Ze2vdXGcErIu9sJX9EXkmiaHSd0GQkgA";
    String cs384 = "eyJhbGciOiJFUzM4NCJ9.VGhlIHVtbGF1dCAoIC8_P21sYT90LyB1dW0tbG93dCkgcmVmZXJzIHRvIGEgc291bmQgc2hpZnQu.UO2zG037CLktsDeHJ71w48DmTMmCjsEEKhFGSE1uBQUG8rRZousdJR8p2rykZglU2RdWG48AE4Rf5_WfiZuP5ANC_bLgiOz1rwlSe6ds2romfdQ-enn7KTvr9Cmqt2Ot";
    String cs512 = "eyJhbGciOiJFUzUxMiJ9.Pz8_Pz8.AJS7SrxiK6zpJkXjV4iWM_oUcE294hV3RK-y5uQD2Otx-UwZNFEH6L66ww5ukQ7R1rykiWd9PNjzlzrgwfJqF2KyASmO6Hz7dZr9EYPIX6rrEpWjsp1tDJ0_Hq45Rk2eJ5z3cFTIpVu6V7CGXwVWvVCDQzcGpmZIFR939aI49Z_HWT7b";
    for (String cs : new String[] {cs256, cs384, cs512})
    {
        JwsTestSupport.testBadKeyOnVerify(cs, ExampleRsaKeyFromJws.PRIVATE_KEY);
        JwsTestSupport.testBadKeyOnVerify(cs, null);
        JwsTestSupport.testBadKeyOnVerify(cs, new HmacKey(new byte[2048]));
        JwsTestSupport.testBadKeyOnVerify(cs, ExampleRsaKeyFromJws.PUBLIC_KEY);
        JwsTestSupport.testBadKeyOnVerify(cs, ExampleEcKeysFromJws.PRIVATE_256);
        JwsTestSupport.testBadKeyOnVerify(cs, ExampleEcKeysFromJws.PRIVATE_521);
    }

    JwsTestSupport.testBadKeyOnVerify(cs256, ExampleEcKeysFromJws.PUBLIC_521);
    JwsTestSupport.testBadKeyOnVerify(cs384, ExampleEcKeysFromJws.PUBLIC_521);
    JwsTestSupport.testBadKeyOnVerify(cs384, ExampleEcKeysFromJws.PUBLIC_256);
    JwsTestSupport.testBadKeyOnVerify(cs512, ExampleEcKeysFromJws.PUBLIC_256);
}
 
Example #10
Source File: JsonWebEncryption.java    From Jose4j with Apache License 2.0 6 votes vote down vote up
protected void setCompactSerializationParts(String[] parts) throws JoseException
{
    if (parts.length != COMPACT_SERIALIZATION_PARTS)
    {
        throw new JoseException("A JWE Compact Serialization must have exactly " + COMPACT_SERIALIZATION_PARTS + " parts separated by period ('.') characters");
    }

    setEncodedHeader(parts[0]);
    encryptedKey = base64url.base64UrlDecode(parts[1]);
    setEncodedIv(parts[2]);
    String encodedCiphertext = parts[3];
    checkNotEmptyPart(encodedCiphertext, "Encoded JWE Ciphertext");
    ciphertext = base64url.base64UrlDecode(encodedCiphertext);
    String encodedAuthenticationTag = parts[4];
    checkNotEmptyPart(encodedAuthenticationTag, "Encoded JWE Authentication Tag");
    byte[] tag = base64url.base64UrlDecode(encodedAuthenticationTag);
    setIntegrity(tag);
}
 
Example #11
Source File: DeflateRFC1951CompressionAlgorithmTest.java    From Jose4j with Apache License 2.0 6 votes vote down vote up
public void testSomeDataCompressedElsewhere() throws JoseException
{
    String s ="q1bKLC5WslLKKCkpKLaK0Y/Rz0wp0EutSMwtyEnVS87PVdLhUkqtKFCyMjQ2NTcyNTW3sACKJJamoGgqRujJL0o" +
            "H6ckqyQSqKMmNLIsMCzWqsPAp8zM3cjINjHdNTPbQizd1BClKTC4CKjICMYtLk4BMp6LMxDylWi4A";
    byte[] decoded = Base64Url.decode(s);
    CompressionAlgorithm ca = new DeflateRFC1951CompressionAlgorithm();
    byte[] decompress = ca.decompress(decoded);
    String decompedString = StringUtil.newStringUtf8(decompress);

    String expected = "{\"iss\":\"https:\\/\\/idp.example.com\",\n" +
            "\"exp\":1357255788,\n" +
            "\"aud\":\"https:\\/\\/sp.example.org\",\n" +
            "\"jti\":\"tmYvYVU2x8LvN72B5Q_EacH._5A\",\n" +
            "\"acr\":\"2\",\n" +
            "\"sub\":\"Brian\"}\n";

    assertEquals(expected, decompedString);
}
 
Example #12
Source File: JsonWebEncryption.java    From Jose4j with Apache License 2.0 6 votes vote down vote up
private void decrypt() throws JoseException
{
    KeyManagementAlgorithm keyManagementModeAlg = getKeyManagementModeAlgorithm();
    ContentEncryptionAlgorithm contentEncryptionAlg = getContentEncryptionAlgorithm();

    ContentEncryptionKeyDescriptor contentEncryptionKeyDesc = contentEncryptionAlg.getContentEncryptionKeyDescriptor();

    if (isDoKeyValidation())
    {
        keyManagementModeAlg.validateDecryptionKey(getKey(), contentEncryptionAlg);
    }

    checkCrit();

    Key cek = keyManagementModeAlg.manageForDecrypt(getKey(), getEncryptedKey(), contentEncryptionKeyDesc, getHeaders(), getProviderCtx());

    ContentEncryptionParts contentEncryptionParts = new ContentEncryptionParts(iv, ciphertext, getIntegrity());
    byte[] aad = getEncodedHeaderAsciiBytesForAdditionalAuthenticatedData();
    byte[] decrypted = contentEncryptionAlg.decrypt(contentEncryptionParts, aad, cek.getEncoded(), getHeaders(), getProviderCtx());

    decrypted = decompress(getHeaders(), decrypted);

    setPlaintext(decrypted);
}
 
Example #13
Source File: IotCoreClient.java    From cloud-iot-core-androidthings with Apache License 2.0 6 votes vote down vote up
private MqttConnectOptions configureConnectionOptions() throws JoseException {
    MqttConnectOptions options = new MqttConnectOptions();

    // Note that the Cloud IoT only supports MQTT 3.1.1, and Paho requires that we
    // explicitly set this. If you don't set MQTT version, the server will immediately close its
    // connection to your device.
    options.setMqttVersion(MqttConnectOptions.MQTT_VERSION_3_1_1);

    // Cloud IoT Core ignores the user name field, but Paho requires a user name in order
    // to send the password field. We set the user name because we need the password to send a
    // JWT to authorize the device.
    options.setUserName("unused");

    // generate the jwt password
    options.setPassword(mJwtGenerator.createJwt().toCharArray());

    return options;
}
 
Example #14
Source File: NegativeJweKeyTest.java    From Jose4j with Apache License 2.0 6 votes vote down vote up
public void testRsaTooSmall() throws JoseException
{
    RsaJsonWebKey rsaJsonWebKey = (RsaJsonWebKey) RsaJsonWebKey.Factory.newPublicJwk("{\"kty\":\"RSA\"," +
            "\"n\":\"hIOFEUa93kqVnqoaA1r5qj3tLhnSyQ9njLrlcJrynwt2LYfIhntUZPfS2fiHhLGzww7GamLAXwDfGZo0dY6V3cglENl6yro" +
            "BWhYu15IgHVAeP1V_5m1gJ9hiWNUR3i5zhNNUR1Ewdo0E52amiRb1-xXRcxhcRlybfRcEMJEgm0c\"," +
            "\"e\":\"AQAB\",\"d\":\"RhNK7jzrsT7d6n7nrLiSaM3AvG1Zg4vK5af8J1U5UpP8Fc3FZCCaG57WeQAtoiVa-563nJDGTDcow-BB" +
            "N52EcG_7SRJtXc6Zk5og330nqIy0OoP2GRPJKOg6zB45RsDQmxklezrlWCMdwZIzjxyB_vDMx59uXK_i66iVXjFoqZk\"," +
            "\"p\":\"7aIngX0swanIMJk-GpmJVxL7vF6Zx0RfmimOE6BJKi7COHR7ectpQtfmYhLMBtMpHF1qnuaa4vlM3S9xLHGlIw\"," +
            "\"q\":\"jsF0PrAmuixIUgCinmh2-FYmBySG8B8Kv_Llj81kKRiNM35Pv_W_zrkb_oxyEMzOc9Z2_gkqhEfYZulnBVCtjQ\"," +
            "\"dp\":\"ab1f6uSyR7Ku28E0u01aqZ5O2fEWaG7qQ4T-LYmDRPvtfIWIdBepTQ8Y-sb2dor7nh2LVg2zGhBovXtg1q_zFQ\"," +
            "\"dq\":\"GPpaZ5mUvSCAavC3g3YN0vfn4XoPrjYQQHO0nQu4CcTE-AyS0aijLf2Pm2NhlfTv7q7I1TwvV0Pm5mLSZsiuBQ\"," +
            "\"qi\":\"gVD_SEwVbiHvZAm3aqynOfMnObl8bBe1qDDNThVO3yUL8tghkKizEu1Ey_sYal-luDu9zcEFUkbrV-7jTqFUVg\"}\n");

    expectBadKeyFailOnProduce(RSA_OAEP, AES_128_CBC_HMAC_SHA_256, rsaJsonWebKey.getPublicKey());
    expectBadKeyFailOnProduce(RSA1_5, AES_128_CBC_HMAC_SHA_256, rsaJsonWebKey.getPublicKey());

    expectBadKeyFailOnConsume("eyJhbGciOiJSU0EtT0FFUCIsImVuYyI6IkExMjhDQkMtSFMyNTYifQ." +
            "Ti9oxDdTy9hk3j5XOu0lPuus3pC6ZPsBY4LubTOKS6kX1XAR16u2yvcf5csZpB-3CK3UL5JQl1kye2QVytWH79FLg2R3Zfjpd21AF" +
            "kjxkkI6Cl9UQjPJCO7oiYnKkBdbMiSwcdGl2z6OHpZNcqHH6jQ4BVk-zDPbg3Vj25X19vE." +
            "pZyCrX1Aae9kvKEyCvUTfA.H7qnqcNKWAVhd-xAVdAgkw.kDaHS6qIiKxAH4Z316EJ6w", rsaJsonWebKey.getPrivateKey());
}
 
Example #15
Source File: JsonWebEncryptionTest.java    From Jose4j with Apache License 2.0 6 votes vote down vote up
@Test
public void testJweExampleA2() throws JoseException
{
    // http://tools.ietf.org/html/draft-ietf-jose-json-web-encryption-14#appendix-A.2
    String jweCsFromAppendixA2 = "eyJhbGciOiJSU0ExXzUiLCJlbmMiOiJBMTI4Q0JDLUhTMjU2In0." +
            "UGhIOguC7IuEvf_NPVaXsGMoLOmwvc1GyqlIKOK1nN94nHPoltGRhWhw7Zx0-kFm" +
            "1NJn8LE9XShH59_i8J0PH5ZZyNfGy2xGdULU7sHNF6Gp2vPLgNZ__deLKxGHZ7Pc" +
            "HALUzoOegEI-8E66jX2E4zyJKx-YxzZIItRzC5hlRirb6Y5Cl_p-ko3YvkkysZIF" +
            "NPccxRU7qve1WYPxqbb2Yw8kZqa2rMWI5ng8OtvzlV7elprCbuPhcCdZ6XDP0_F8" +
            "rkXds2vE4X-ncOIM8hAYHHi29NX0mcKiRaD0-D-ljQTP-cFPgwCp6X-nZZd9OHBv" +
            "-B3oWh2TbqmScqXMR4gp_A." +
            "AxY8DCtDaGlsbGljb3RoZQ." +
            "KDlTtXchhZTGufMYmOYGS4HffxPSUrfmqCHXaI9wOGY." +
            "9hH0vgRfYgPnAHOd8stkvw";

    JsonWebEncryption jwe = new JsonWebEncryption();
    jwe.setKey(ExampleRsaJwksFromJwe.APPENDIX_A_2.getPrivateKey());
    jwe.setCompactSerialization(jweCsFromAppendixA2);
    String plaintextString = jwe.getPlaintextString();
    assertEquals("Live long and prosper.", plaintextString);
}
 
Example #16
Source File: Pbkdf2MoreTest.java    From Jose4j with Apache License 2.0 5 votes vote down vote up
@Test
public void test6() throws JoseException
{
    int ic = 3;
    String encodedSalt = "SldHVNgHJadJ";
    int dklenBytes = 128;
    String pwd = "dabears";
    String prn = "HmacSHA256";
    String pbk = "nperkSKKFADfulz5xpNkvBrbLK6z075ZUgssE72EWY0vbijZo1rT8pyBhS-hHLcXJi03LXb0E8383sIYjsZInH5OupD" +
            "4dLWXLiE4ZTB1HV8dESTwQug_M7EqVKqIbGW2HV2k5CQUfN2cK9V1U3Jmi0oEJps2fS12jXlMqbNA--Y";
    testIt(ic, encodedSalt, dklenBytes, pwd, prn, pbk);

}
 
Example #17
Source File: JwsPlaintextTest.java    From Jose4j with Apache License 2.0 5 votes vote down vote up
@Test
public void testADecode() throws JoseException
{
    String cs = "eyJhbGciOiJub25lIn0.eyJhdXRoX3RpbWUiOjEzMzk2MTMyNDgsImV4cCI6MTMzOTYxMzU0OCwiaXNzIjoiaHR0cHM6XC9cL2V4YW1wbGUuY29tIiwiYXVkIjoiYSIsImp0aSI6ImpJQThxYTM1QXJvVjZpUDJxNHdSQWwiLCJ1c2VyX2lkIjoiam9obiIsImlhdCI6MTMzOTYxMzI0OCwiYWNyIjozfQ.";
    JsonWebSignature jws = new JsonWebSignature();
    jws.setAlgorithmConstraints(AlgorithmConstraints.NO_CONSTRAINTS);
    jws.setCompactSerialization(cs);
    assertTrue(jws.verifySignature());
    String payload = jws.getPayload();
    log.debug(payload);
}
 
Example #18
Source File: KeySet.java    From datamill with ISC License 5 votes vote down vote up
public KeySet(String keySetJson) {
    try {
        JsonWebKeySet keySet = new JsonWebKeySet(keySetJson);
        for (JsonWebKey key : keySet.getJsonWebKeys()) {
            if (key instanceof PublicJsonWebKey) {
                keys.add(new JsonKeyPairImpl(key));
            } else {
                keys.add(new JsonKeyImpl(key));
            }
        }
    } catch (JoseException e) {
        throw new SecurityException(e);
    }
}
 
Example #19
Source File: RsaJsonWebKeyTest.java    From Jose4j with Apache License 2.0 5 votes vote down vote up
@Test
public void testFromCrtAndBackWithJwsAppendixA2() throws JoseException
{
    String json =
            "     {\"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" +
            "      \"p\":\"4BzEEOtIpmVdVEZNCqS7baC4crd0pqnRH_5IB3jw3bcxGn6QLvnEtfdUdi\n" +
            "           YrqBdss1l58BQ3KhooKeQTa9AB0Hw_Py5PJdTJNPY8cQn7ouZ2KKDcmnPG\n" +
            "           BY5t7yLc1QlQ5xHdwW1VhvKn-nXqhJTBgIPgtldC-KDV5z-y2XDwGUc\",\n" +
            "      \"q\":\"uQPEfgmVtjL0Uyyx88GZFF1fOunH3-7cepKmtH4pxhtCoHqpWmT8YAmZxa\n" +
            "           ewHgHAjLYsp1ZSe7zFYHj7C6ul7TjeLQeZD_YwD66t62wDmpe_HlB-TnBA\n" +
            "           -njbglfIsRLtXlnDzQkv5dTltRJ11BKBBypeeF6689rjcJIDEz9RWdc\",\n" +
            "      \"dp\":\"BwKfV3Akq5_MFZDFZCnW-wzl-CCo83WoZvnLQwCTeDv8uzluRSnm71I3Q\n" +
            "           CLdhrqE2e9YkxvuxdBfpT_PI7Yz-FOKnu1R6HsJeDCjn12Sk3vmAktV2zb\n" +
            "           34MCdy7cpdTh_YVr7tss2u6vneTwrA86rZtu5Mbr1C1XsmvkxHQAdYo0\",\n" +
            "      \"dq\":\"h_96-mK1R_7glhsum81dZxjTnYynPbZpHziZjeeHcXYsXaaMwkOlODsWa\n" +
            "           7I9xXDoRwbKgB719rrmI2oKr6N3Do9U0ajaHF-NKJnwgjMd2w9cjz3_-ky\n" +
            "           NlxAr2v4IKhGNpmM5iIgOS1VZnOZ68m6_pbLBSp3nssTdlqvd0tIiTHU\",\n" +
            "      \"qi\":\"IYd7DHOhrWvxkwPQsRM2tOgrjbcrfvtQJipd-DlcxyVuuM9sQLdgjVk2o\n" +
            "           y26F0EmpScGLq2MowX7fhd_QJQ3ydy5cY7YIBi87w93IKLEdfnbJtoOPLU\n" +
            "           W0ITrJReOgo1cq9SbsxYawBgfp_gh6A5603k2-ZQwVK0JKSHuLFkuQ3U\"\n" +
            "     }";
    doKeyWithCrtPrivateAndBackAndAgain(json);
}
 
Example #20
Source File: ProviderContextTest.java    From Jose4j with Apache License 2.0 5 votes vote down vote up
void expectNoProviderProduce(JsonWebStructure jwx)
{
    try
    {
        String compactSerialization = jwx.getCompactSerialization();
        Assert.fail("Shouldn't have gotten compact serialization " + compactSerialization);
    }
    catch (JoseException e)
    {
        Assert.assertThat(e.getMessage(), CoreMatchers.containsString(NO_SUCH_PROVIDER));
    }
}
 
Example #21
Source File: Http2ClientTest.java    From light-4j with Apache License 2.0 5 votes vote down vote up
public static String getJwt(JwtClaims claims) throws JoseException {
    String jwt;

    RSAPrivateKey privateKey = (RSAPrivateKey) getPrivateKey(
            "/config/primary.jks", "password", "selfsigned");

    // A JWT is a JWS and/or a JWE with JSON claims as the payload.
    // In this example it is a JWS nested inside a JWE
    // So we first create a JsonWebSignature object.
    JsonWebSignature jws = new JsonWebSignature();

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

    // The JWT is signed using the sender's private key
    jws.setKey(privateKey);
    jws.setKeyIdHeaderValue("100");

    // Set the signature algorithm on the JWT/JWS that will integrity protect the claims
    jws.setAlgorithmHeaderValue(AlgorithmIdentifiers.RSA_USING_SHA256);

    // Sign the JWS and produce the compact serialization, which will be the inner JWT/JWS
    // representation, which is a string consisting of three dot ('.') separated
    // base64url-encoded parts in the form Header.Payload.Signature
    jwt = jws.getCompactSerialization();
    return jwt;
}
 
Example #22
Source File: Http2ClientIT.java    From light-4j with Apache License 2.0 5 votes vote down vote up
public static String getJwt(JwtClaims claims) throws JoseException {
    String jwt;

    RSAPrivateKey privateKey = (RSAPrivateKey) getPrivateKey(
            "/config/primary.jks", "password", "selfsigned");

    // A JWT is a JWS and/or a JWE with JSON claims as the payload.
    // In this example it is a JWS nested inside a JWE
    // So we first create a JsonWebSignature object.
    JsonWebSignature jws = new JsonWebSignature();

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

    // The JWT is signed using the sender's private key
    jws.setKey(privateKey);
    jws.setKeyIdHeaderValue("100");

    // Set the signature algorithm on the JWT/JWS that will integrity protect the claims
    jws.setAlgorithmHeaderValue(AlgorithmIdentifiers.RSA_USING_SHA256);

    // Sign the JWS and produce the compact serialization, which will be the inner JWT/JWS
    // representation, which is a string consisting of three dot ('.') separated
    // base64url-encoded parts in the form Header.Payload.Signature
    jwt = jws.getCompactSerialization();
    return jwt;
}
 
Example #23
Source File: Pbkdf2MoreTest.java    From Jose4j with Apache License 2.0 5 votes vote down vote up
@Test
public void test5() throws JoseException
{
    int ic = 1;
    String encodedSalt = "WKSJ8q-EvvyP-0RQd6g";
    int dklenBytes = 16;
    String pwd = "blahblahblahblah";
    String prn = "HmacSHA256";
    String pbk = "6a1-B_PrQu-Pfi9-6w_Y5A";
    testIt(ic, encodedSalt, dklenBytes, pwd, prn, pbk);
}
 
Example #24
Source File: JwtClaims.java    From Jose4j with Apache License 2.0 5 votes vote down vote up
private JwtClaims(String jsonClaims) throws InvalidJwtException
{
    rawJson = jsonClaims;
    try
    {
        Map<String, Object> parsed = JsonUtil.parseJson(jsonClaims);
        claimsMap = new LinkedHashMap<>(parsed);
    }
    catch (JoseException e)
    {
        throw new InvalidJwtException("Unable to parse JWT Claim Set JSON: " + jsonClaims, e);
    }
}
 
Example #25
Source File: EllipticCurveJsonWebKeyTest.java    From Jose4j with Apache License 2.0 5 votes vote down vote up
@Test
public void testToJsonWithPublicKeyOnlyJWKAndIncludePrivateSettings() throws JoseException
   {
       PublicJsonWebKey jwk = PublicJsonWebKey.Factory.newPublicJwk(ExampleEcKeysFromJws.PUBLIC_521);
       String jsonNoPrivateKey = jwk.toJson(PUBLIC_ONLY);
       PublicJsonWebKey publicOnlyJWK = PublicJsonWebKey.Factory.newPublicJwk(jsonNoPrivateKey);
       assertThat(jsonNoPrivateKey,is(equalTo(publicOnlyJWK.toJson(INCLUDE_PRIVATE))));
}
 
Example #26
Source File: JwtTokenVerifierImpl.java    From blueocean-plugin with MIT License 5 votes vote down vote up
private JsonWebStructure parse(String token) {
    try {
        return JsonWebStructure.fromCompactSerialization(token);
    } catch (JoseException e) {
        // token was not formed as JWT token. Probably it's a different kind of bearer token
        // some other plugins have introduced
        return null;
    }
}
 
Example #27
Source File: Pbes2HmacShaWithAesKeyWrapAlgorithmTest.java    From Jose4j with Apache License 2.0 5 votes vote down vote up
@Test (expected = InvalidKeyException.class)
public void testNullKey() throws JoseException
{
    JsonWebEncryption encryptingJwe  = new JsonWebEncryption();
    encryptingJwe.setAlgorithmHeaderValue(PBES2_HS256_A128KW);
    encryptingJwe.setEncryptionMethodHeaderParameter(AES_128_CBC_HMAC_SHA_256);
    encryptingJwe.setPayload("meh");

    encryptingJwe.getCompactSerialization();
}
 
Example #28
Source File: Pbes2HmacShaWithAesKeyWrapAlgorithmTest.java    From Jose4j with Apache License 2.0 5 votes vote down vote up
@Test
public void testSettingSaltAndIterationCount() throws JoseException
{
    String password = "secret word";
    String plaintext = "<insert some witty quote or remark here, again>";

    JsonWebEncryption encryptingJwe  = new JsonWebEncryption();
    int saltByteLength = 32;
    String saltInputString = Base64Url.encode(ByteUtil.randomBytes(saltByteLength));
    encryptingJwe.getHeaders().setStringHeaderValue(HeaderParameterNames.PBES2_SALT_INPUT, saltInputString);
    long iterationCount = 1024L;
    encryptingJwe.getHeaders().setObjectHeaderValue(HeaderParameterNames.PBES2_ITERATION_COUNT, iterationCount);

    encryptingJwe.setAlgorithmHeaderValue(PBES2_HS384_A192KW);
    encryptingJwe.setEncryptionMethodHeaderParameter(AES_192_CBC_HMAC_SHA_384);
    encryptingJwe.setPayload(plaintext);
    encryptingJwe.setKey(new PbkdfKey(password));
    String compactSerialization = encryptingJwe.getCompactSerialization();

    JsonWebEncryption decryptingJwe = new JsonWebEncryption();
    decryptingJwe.setCompactSerialization(compactSerialization);
    decryptingJwe.setKey(new PbkdfKey(password));
    assertThat(plaintext, equalTo(decryptingJwe.getPayload()));

    String saltInputStringFromHeader = decryptingJwe.getHeader(HeaderParameterNames.PBES2_SALT_INPUT);
    assertThat(saltInputString, equalTo(saltInputStringFromHeader));
    assertThat(saltByteLength, equalTo(Base64Url.decode(saltInputStringFromHeader).length));
    long iterationCountFromHeader = decryptingJwe.getHeaders().getLongHeaderValue(HeaderParameterNames.PBES2_ITERATION_COUNT);
    assertThat(iterationCount, equalTo(iterationCountFromHeader));
}
 
Example #29
Source File: JsonWebKeyTest.java    From Jose4j with Apache License 2.0 5 votes vote down vote up
static void checkEncoding(String jwkJson, String... members) throws JoseException
{
    Map<String,Object> parsed = JsonUtil.parseJson(jwkJson);
    for (String name : members)
    {
        // not base64
        String value = (String)parsed.get(name);
        assertEquals(-1, value.indexOf('\r'));
        assertEquals(-1, value.indexOf('\n'));
        assertEquals(-1, value.indexOf('='));
        assertEquals(-1, value.indexOf('+'));
        assertEquals(-1, value.indexOf('/'));
    }
}
 
Example #30
Source File: JsonWebKey.java    From Jose4j with Apache License 2.0 5 votes vote down vote up
protected static String getString(Map<String, Object> params, String name, boolean required) throws JoseException
{
    String value = getString(params, name);
    if (value == null && required)
    {
        throw new JoseException("Missing required '" + name + "' parameter.");
    }

    return value;
}