org.jose4j.jwe.JsonWebEncryption Java Examples

The following examples show how to use org.jose4j.jwe.JsonWebEncryption. 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: JwtEncryptionImpl.java    From smallrye-jwt with Apache License 2.0 7 votes vote down vote up
private String encryptInternal(Key key) {
    JsonWebEncryption jwe = new JsonWebEncryption();
    jwe.setPlaintext(claims);
    for (Map.Entry<String, Object> entry : headers.entrySet()) {
        jwe.getHeaders().setObjectHeaderValue(entry.getKey(), entry.getValue());
    }
    if (innerSigned && !headers.containsKey("cty")) {
        jwe.getHeaders().setObjectHeaderValue("cty", "JWT");
    }
    String keyAlgorithm = getKeyEncryptionAlgorithm(key);
    jwe.setAlgorithmHeaderValue(keyAlgorithm);
    jwe.setEncryptionMethodHeaderParameter(getContentEncryptionAlgorithm());

    if (key instanceof RSAPublicKey && keyAlgorithm.startsWith(KeyEncryptionAlgorithm.RSA_OAEP.getAlgorithm())
            && ((RSAPublicKey) key).getModulus().bitLength() < 2048) {
        throw ImplMessages.msg.encryptionKeySizeMustBeHigher(keyAlgorithm);
    }
    jwe.setKey(key);
    try {
        return jwe.getCompactSerialization();
    } catch (org.jose4j.lang.JoseException ex) {
        throw ImplMessages.msg.joseSerializationError(ex.getMessage(), ex);
    }
}
 
Example #2
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 #3
Source File: JsonWebStructureTest.java    From Jose4j with Apache License 2.0 6 votes vote down vote up
@Test
public void jwe1() throws JoseException
{
    String cs = "eyJhbGciOiJkaXIiLCJlbmMiOiJBMTI4Q0JDLUhTMjU2Iiwia2lkIjoiOWVyIn0." +
            "." +
            "XAog2l7TP5-0mIPYjT2ZYg." +
            "Zf6vQZhxeAfzk2AyuXsKJSo1R8aluPDvK7a6N7wvSmuIUczDhUtJFmNdXC3d4rPa." +
            "XBTguLfGeGKu6YsQVnes2w";
    JsonWebStructure jwx = JsonWebStructure.fromCompactSerialization(cs);
    jwx.setKey(oct256bitJwk.getKey());
    Assert.assertTrue(cs + " should give a JWE " + jwx, jwx instanceof JsonWebEncryption);
    Assert.assertEquals(KeyManagementAlgorithmIdentifiers.DIRECT, jwx.getAlgorithmHeaderValue());
    Assert.assertEquals(oct256bitJwk.getKeyId(), jwx.getKeyIdHeaderValue());
    String payload = jwx.getPayload();
    Assert.assertEquals(YOU_LL_GET_NOTHING_AND_LIKE_IT, payload);
}
 
Example #4
Source File: JwtConsumerTest.java    From Jose4j with Apache License 2.0 6 votes vote down vote up
private void littleJweRoundTrip(String alg, String enc, String b64uKey) throws Exception
{
    byte[] raw = Base64Url.decode(b64uKey);
    Key key = new FakeHsmNonExtractableSecretKeySpec(raw, "AES");
    JwtClaims claims = new JwtClaims();
    claims.setExpirationTimeMinutesInTheFuture(5);
    claims.setSubject("subject");
    claims.setIssuer("issuer");
    JsonWebEncryption jwe = new JsonWebEncryption();
    jwe.setPayload(claims.toJson());
    jwe.setAlgorithmHeaderValue(alg);
    jwe.setEncryptionMethodHeaderParameter(enc);
    jwe.setKey(key);

    String jwt = jwe.getCompactSerialization();
    JwtConsumerBuilder jwtConsumerBuilder = new JwtConsumerBuilder();
    jwtConsumerBuilder.setAllowedClockSkewInSeconds(60);
    jwtConsumerBuilder.setRequireSubject();
    jwtConsumerBuilder.setExpectedIssuer("issuer");
    jwtConsumerBuilder.setDecryptionKey(key);
    jwtConsumerBuilder.setDisableRequireSignature();
    JwtConsumer jwtConsumer = jwtConsumerBuilder.build();
    JwtClaims processedClaims = jwtConsumer.processToClaims(jwt);
    Assert.assertThat(processedClaims.getSubject(), equalTo("subject"));
}
 
Example #5
Source File: Jose4jJoseImpl.java    From thorntail with Apache License 2.0 6 votes vote down vote up
@Override
public String encrypt(EncryptionInput input) {
    JsonWebEncryption jwe = new JsonWebEncryption();
    jwe.setPlaintext(input.getData());
    for (Map.Entry<String, Object> entry : input.getHeaders().entrySet()) {
        jwe.getHeaders().setObjectHeaderValue(entry.getKey(), entry.getValue());
    }
    jwe.setAlgorithmHeaderValue(config.keyEncryptionAlgorithm());
    jwe.setEncryptionMethodHeaderParameter(config.contentEncryptionAlgorithm());
    if (config.includeEncryptionKeyAlias()) {
        jwe.setKeyIdHeaderValue(encryptionKeyAlias());
    }
    jwe.setKey(getEncryptionKey(jwe, JoseOperation.ENCRYPTION));
    try {
        return jwe.getCompactSerialization();
    } catch (org.jose4j.lang.JoseException ex) {
        throw new JoseException(ex.getMessage(), ex);
    }
}
 
Example #6
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 #7
Source File: TokenUtils.java    From microprofile-jwt-auth with Apache License 2.0 6 votes vote down vote up
private static String encryptString(Key key, String kid, String plainText, boolean setContentType) throws Exception {

        JsonWebEncryption jwe = new JsonWebEncryption();
        jwe.setPlaintext(plainText);
        if (kid != null) {
            jwe.setKeyIdHeaderValue(kid);
        }
        if (setContentType && plainText.split("\\.").length == 3) {
            // nested JWT
            jwe.setHeader("cty", "JWT");
        }
        jwe.setEncryptionMethodHeaderParameter("A256GCM");

        if (key instanceof SecretKey) {
            jwe.setAlgorithmHeaderValue("A128KW");
        }
        else {
            jwe.setAlgorithmHeaderValue("RSA-OAEP");
        }
        jwe.setKey(key);
        return jwe.getCompactSerialization();
    }
 
Example #8
Source File: TokenHelper.java    From git-as-svn with GNU General Public License v2.0 6 votes vote down vote up
@NotNull
public static String createToken(@NotNull JsonWebEncryption jwe, @NotNull User user, @NotNull NumericDate expireAt) {
  try {
    JwtClaims claims = new JwtClaims();
    claims.setExpirationTime(expireAt);
    claims.setGeneratedJwtId(); // a unique identifier for the token
    claims.setIssuedAtToNow();  // when the token was issued/created (now)
    claims.setNotBeforeMinutesInThePast(0.5f); // time before which the token is not yet valid (30 seconds ago)
    if (!user.isAnonymous()) {
      claims.setSubject(user.getUsername()); // the subject/principal is whom the token is about
      setClaim(claims, "email", user.getEmail());
      setClaim(claims, "name", user.getRealName());
      setClaim(claims, "external", user.getExternalId());
      setClaim(claims, "type", user.getType().name());
    }
    jwe.setPayload(claims.toJson());
    return jwe.getCompactSerialization();
  } catch (JoseException e) {
    throw new IllegalStateException(e);
  }
}
 
Example #9
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 #10
Source File: JsonWebStructureTest.java    From Jose4j with Apache License 2.0 5 votes vote down vote up
@Test (expected = IntegrityException.class)
public void integrityCheckFailsJwe() throws JoseException
{
    String cs = "eyJhbGciOiJBMjU2S1ciLCJlbmMiOiJBMTI4Q0JDLUhTMjU2Iiwia2lkIjoiOWVyIn0." +
            "RAqGCBMFk7O-B-glFckcFmxUr8BTTXuZk-bXAdRZxpk5Vgs_1yoUQw." +
            "hyl68_ADlK4VRDYiQMQS6w." +
            "xk--JKIVF4Xjxc0gRGPL30s4PSNtj685WYqXbjyItG0uSffD4ajGXdz4BO8i0sbM." +
            "aXaAVpBgftxqO1HkkRvgab";
    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());
    jwx.getPayload();
}
 
Example #11
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 #12
Source File: Jose4jJoseImpl.java    From thorntail with Apache License 2.0 5 votes vote down vote up
private Key getEncryptionKey(JsonWebEncryption jwe, JoseOperation operation) {
    if ("jwk".equals(this.config.keystoreType())) {
        return getJwkKey((operation.equals(JoseOperation.ENCRYPTION) ? encryptionKeyAlias() : decryptionKeyAlias(jwe)),
                config.contentEncryptionAlgorithm());

    } else if (operation.equals(JoseOperation.ENCRYPTION)) {
        return getJavaStorePublicKey(encryptionKeyAlias());

    } else {
        return getJavaStorePrivateKey(decryptionKeyAlias(jwe), config.encryptionKeyPassword());
    }
}
 
Example #13
Source File: Jose4jJoseImpl.java    From thorntail with Apache License 2.0 5 votes vote down vote up
private String decryptionKeyAlias(JsonWebEncryption jwe) {

        if (config.acceptEncryptionAlias()) {
            return jwe.getKeyIdHeaderValue();
        }
        if (config.encryptionKeyAliasIn() == null) {
            return config.encryptionKeyAlias();
        }
        return config.encryptionKeyAliasIn();
    }
 
Example #14
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 #15
Source File: DefaultCipherExecutor.java    From nano-framework with Apache License 2.0 5 votes vote down vote up
/**
 * Encrypt the value based on the seed array whose length was given during init,
 * and the key and content encryption ids.
 *
 * @param value the value
 * @return the encoded value
 */
private String encryptValue(@NotNull final String value) {
    try {
        final JsonWebEncryption jwe = new JsonWebEncryption();
        jwe.setPayload(value);
        jwe.setAlgorithmHeaderValue(KeyManagementAlgorithmIdentifiers.DIRECT);
        jwe.setEncryptionMethodHeaderParameter(this.contentEncryptionAlgorithmIdentifier);
        jwe.setKey(this.secretKeyEncryptionKey);
        LOGGER.debug("Encrypting via [{}]", this.contentEncryptionAlgorithmIdentifier);
        return jwe.getCompactSerialization();
    } catch (final Exception e) {
        throw new RuntimeException("Ensure that you have installed JCE Unlimited Strength Jurisdiction Policy Files. " + e.getMessage(), e);
    }
}
 
Example #16
Source File: DefaultCipherExecutor.java    From nano-framework with Apache License 2.0 5 votes vote down vote up
/**
 * Decrypt value based on the key created during init.
 *
 * @param value the value
 * @return the decrypted value
 */
private String decryptValue(@NotNull final String value) {
    try {
        final JsonWebEncryption jwe = new JsonWebEncryption();
        jwe.setKey(this.secretKeyEncryptionKey);
        jwe.setCompactSerialization(value);
        LOGGER.debug("Decrypting value...");
        return jwe.getPayload();
    } catch (final Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example #17
Source File: DefaultCipherExecutor.java    From springboot-shiro-cas-mybatis with MIT License 5 votes vote down vote up
/**
 * Decrypt value based on the key created during init.
 *
 * @param value the value
 * @return the decrypted value
 */
private String decryptValue(@NotNull final String value) {
    try {
        final JsonWebEncryption jwe = new JsonWebEncryption();
        jwe.setKey(this.secretKeyEncryptionKey);
        jwe.setCompactSerialization(value);
        logger.debug("Decrypting value...");
        return jwe.getPayload();
    } catch (final Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example #18
Source File: DefaultCipherExecutor.java    From springboot-shiro-cas-mybatis with MIT License 5 votes vote down vote up
/**
 * Encrypt the value based on the seed array whose length was given during init,
 * and the key and content encryption ids.
 *
 * @param value the value
 * @return the encoded value
 */
private String encryptValue(@NotNull final String value) {
    try {
        final JsonWebEncryption jwe = new JsonWebEncryption();
        jwe.setPayload(value);
        jwe.setAlgorithmHeaderValue(KeyManagementAlgorithmIdentifiers.DIRECT);
        jwe.setEncryptionMethodHeaderParameter(this.contentEncryptionAlgorithmIdentifier);
        jwe.setKey(this.secretKeyEncryptionKey);
        logger.debug("Encrypting via [{}]", this.contentEncryptionAlgorithmIdentifier);
        return jwe.getCompactSerialization();
    } catch (final Exception e) {
        throw new RuntimeException("Ensure that you have installed JCE Unlimited Strength Jurisdiction Policy Files. "
                + e.getMessage(), e);
    }
}
 
Example #19
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 #20
Source File: DecryptPioneerPayloads.java    From gcp-ingestion with Mozilla Public License 2.0 5 votes vote down vote up
/**
 * Decrypt a payload encoded in a compact serialization of JSON Web Encryption (JWE).
 */
public static byte[] decrypt(PrivateKey key, String payload) throws JoseException {
  JsonWebEncryption jwe = new JsonWebEncryption();
  jwe.setKey(key);
  jwe.setContentEncryptionKey(key.getEncoded());
  jwe.setCompactSerialization(payload);
  return jwe.getPlaintextBytes();
}
 
Example #21
Source File: PioneerBenchmarkGenerator.java    From gcp-ingestion with Mozilla Public License 2.0 5 votes vote down vote up
/** Encrypt a payload using a public key. */
public static String encrypt(byte[] data, PublicKey key) throws IOException, JoseException {
  JsonWebEncryption jwe = new JsonWebEncryption();
  jwe.setPayload(new String(data, Charsets.UTF_8));
  jwe.setAlgorithmHeaderValue(KeyManagementAlgorithmIdentifiers.ECDH_ES);
  jwe.setEncryptionMethodHeaderParameter(ContentEncryptionAlgorithmIdentifiers.AES_256_GCM);
  jwe.setKey(key);
  return jwe.getCompactSerialization();
}
 
Example #22
Source File: TokenHelper.java    From git-as-svn with GNU General Public License v2.0 5 votes vote down vote up
@Nullable
public static User parseToken(@NotNull JsonWebEncryption jwe, @NotNull String token, int tokenEnsureTime) {
  try {
    jwe.setCompactSerialization(token);
    final JwtClaims claims = JwtClaims.parse(jwe.getPayload());
    final NumericDate now = NumericDate.now();
    final NumericDate expire = NumericDate.fromMilliseconds(now.getValueInMillis());
    if (tokenEnsureTime > 0) {
      expire.addSeconds(tokenEnsureTime);
    }
    if (claims.getExpirationTime() == null || claims.getExpirationTime().isBefore(expire)) {
      return null;
    }
    if (claims.getNotBefore() == null || claims.getNotBefore().isAfter(now)) {
      return null;
    }
    if (claims.getSubject() == null) {
      return User.getAnonymous();
    }
    return User.create(
        claims.getSubject(),
        claims.getClaimValue("name", String.class),
        claims.getClaimValue("email", String.class),
        claims.getClaimValue("external", String.class),
        UserType.valueOf(claims.getClaimValue("type", String.class)),
        null
    );
  } catch (JoseException | MalformedClaimException | InvalidJwtException e) {
    log.warn("Token parsing error: " + e.getMessage());
    return null;
  }
}
 
Example #23
Source File: EncryptionFactoryAes.java    From git-as-svn with GNU General Public License v2.0 5 votes vote down vote up
@NotNull
@Override
public JsonWebEncryption create() {
  final JsonWebEncryption jwe = new JsonWebEncryption();
  jwe.setAlgorithmHeaderValue(KeyManagementAlgorithmIdentifiers.A128KW);
  jwe.setEncryptionMethodHeaderParameter(ContentEncryptionAlgorithmIdentifiers.AES_128_CBC_HMAC_SHA_256);
  jwe.setKey(key);
  return jwe;
}
 
Example #24
Source File: JwtConsumerTest.java    From Jose4j with Apache License 2.0 4 votes vote down vote up
@Test
public void ctyRoundTrip() throws JoseException, InvalidJwtException, MalformedClaimException
{
    JsonWebKeySet jwks = new JsonWebKeySet("{\"keys\":[" +
            "{\"kty\":\"oct\",\"kid\":\"hk1\",\"alg\":\"HS256\",\"k\":\"RYCCH0Qai_7Clk_GnfBElTFIa5VJP3pJUDd8g5H0PKs\"}," +
            "{\"kty\":\"oct\",\"kid\":\"ek1\",\"alg\":\"A128KW\",\"k\":\"Qi38jqNMENlgKaVRbhKWnQ\"}]}");

    SimpleJwkFilter filter = new SimpleJwkFilter();
    filter.setKid("hk1", false);
    JsonWebKey hmacKey = filter.filter(jwks.getJsonWebKeys()).iterator().next();

    filter = new SimpleJwkFilter();
    filter.setKid("ek1", false);
    JsonWebKey encKey = filter.filter(jwks.getJsonWebKeys()).iterator().next();

    JwtClaims claims = new JwtClaims();
    claims.setSubject("subject");
    claims.setAudience("audience");
    claims.setIssuer("issuer");
    claims.setExpirationTimeMinutesInTheFuture(10);
    claims.setNotBeforeMinutesInThePast(5);
    claims.setGeneratedJwtId();

    JsonWebSignature jws = new JsonWebSignature();
    jws.setAlgorithmHeaderValue(AlgorithmIdentifiers.HMAC_SHA256);
    jws.setPayload(claims.toJson());
    jws.setKey(hmacKey.getKey());
    jws.setKeyIdHeaderValue(hmacKey.getKeyId());
    String innerJwt = jws.getCompactSerialization();

    JsonWebEncryption jwe = new JsonWebEncryption();
    jwe.setAlgorithmHeaderValue(KeyManagementAlgorithmIdentifiers.A128KW);
    jwe.setEncryptionMethodHeaderParameter(ContentEncryptionAlgorithmIdentifiers.AES_128_CBC_HMAC_SHA_256);
    jwe.setKey(encKey.getKey());
    jwe.setKeyIdHeaderValue(encKey.getKeyId());
    jwe.setContentTypeHeaderValue("JWT");
    jwe.setPayload(innerJwt);
    String jwt = jwe.getCompactSerialization();

    JwtConsumer jwtConsumer = new JwtConsumerBuilder()
            .setExpectedIssuer("issuer")
            .setExpectedAudience("audience")
            .setRequireSubject()
            .setRequireExpirationTime()
            .setDecryptionKey(encKey.getKey())
            .setVerificationKey(hmacKey.getKey())
            .build();

    JwtContext jwtContext = jwtConsumer.process(jwt);
    Assert.assertThat("subject", equalTo(jwtContext.getJwtClaims().getSubject()));
    List<JsonWebStructure> joseObjects = jwtContext.getJoseObjects();
    JsonWebStructure outerJsonWebObject = joseObjects.get(joseObjects.size() - 1);
    Assert.assertTrue(outerJsonWebObject instanceof JsonWebEncryption);
    Assert.assertThat("JWT", equalTo(outerJsonWebObject.getContentTypeHeaderValue()));
    Assert.assertThat("JWT", equalTo(outerJsonWebObject.getHeader(HeaderParameterNames.CONTENT_TYPE)));
    Assert.assertThat("JWT", equalTo(outerJsonWebObject.getHeaders().getStringHeaderValue(HeaderParameterNames.CONTENT_TYPE)));
    JsonWebStructure innerJsonWebObject = joseObjects.get(0);
    Assert.assertTrue(innerJsonWebObject instanceof JsonWebSignature);
}
 
Example #25
Source File: JWT_Encrypted_Creator_Callout.java    From iloveapis2015-jwt-jwe-jws with Apache License 2.0 4 votes vote down vote up
public ExecutionResult execute (MessageContext msgCtxt,
                                ExecutionContext exeCtxt) {

    String varName;
    try {
        //JWTClaimsSet claims = new JWTClaimsSet();
        JwtClaims claims = new JwtClaims();
        String ISSUER = getIssuer(msgCtxt);
        claims.setIssuer(ISSUER);
        Float expirationInMinutes = Float.valueOf(getExpirationInMinutes(msgCtxt));
        claims.setExpirationTimeMinutesInTheFuture(expirationInMinutes);
        String uniqueID = UUID.randomUUID().toString();
        claims.setJwtId(uniqueID);

        /***************************SENDER'S END ***********************************/
        claims.setSubject("users");
        claims.setClaim("email", "users@test.com");
        claims.setClaim("Country", "USA");
        claims.setClaim("active", "true");
        claims.setClaim("dealerId", "1234");
        claims.setClaim("url", "www.mycompany.com");

        RSAPublicKey publicKey = (RSAPublicKey) getPublicKey(msgCtxt);
        KeyGenerator keyGen = KeyGenerator.getInstance("AES");
        keyGen.init(256);
        SecretKey contentEncryptKey = keyGen.generateKey();

        JsonWebEncryption jwe = new JsonWebEncryption();
        jwe.setKey(publicKey);
        jwe.setPayload(claims.toJson());
        jwe.setAlgorithmHeaderValue(KeyManagementAlgorithmIdentifiers.RSA_OAEP_256);
        jwe.setContentEncryptionKey(contentEncryptKey.getEncoded());
        jwe.setEncryptionMethodHeaderParameter(ContentEncryptionAlgorithmIdentifiers.AES_128_CBC_HMAC_SHA_256);
        SecureRandom iv = SecureRandom.getInstance("SHA1PRNG");
        jwe.setIv(iv.generateSeed(16));
        String encryptedJwt = jwe.getCompactSerialization();
        System.out.println("Encrypted ::" + encryptedJwt);
        varName = getVarname("encryptedJwt");
        msgCtxt.setVariable(varName, encryptedJwt);
    }

    catch (Exception e) {
        //e.printStackTrace();
        varName = getVarname( "error");
        msgCtxt.setVariable(varName, "Exception (A): " + e.toString());
        System.out.println("exception: " + e.toString());
        varName = getVarname("stacktrace");
        msgCtxt.setVariable(varName, "Stack (A): " + ExceptionUtils.getStackTrace(e));
        return ExecutionResult.ABORT;
    }
    return ExecutionResult.SUCCESS;

}
 
Example #26
Source File: JweDecryptorCallout.java    From iloveapis2015-jwt-jwe-jws with Apache License 2.0 4 votes vote down vote up
public ExecutionResult execute(MessageContext msgCtxt, ExecutionContext exeCtxt)
{
    try {
        msgCtxt.removeVariable(varName("error"));
        String jweText = getJweCompactSerialization(msgCtxt);
        String secretKey = getSecretKey(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();

        // Set the compact serialization on new Json Web Encryption object
        jwe.setCompactSerialization(jweText);
        jwe.setKey(jwk.getKey());

        // Get the message that was encrypted in the JWE. This step
        // performs the actual decryption steps.
        String plaintext = jwe.getPlaintextString();
        msgCtxt.setVariable(varName("plaintext"), plaintext);

        String foundAlgorithm = jwe.getEncryptionMethodHeaderParameter();
        msgCtxt.setVariable(varName("algorithm"), foundAlgorithm);
        if (!StringUtils.isEmpty(foundAlgorithm)) {
            String requiredAlgorithm = getAlgorithm(msgCtxt);

            if (! foundAlgorithm.equals(requiredAlgorithm)) {
                msgCtxt.setVariable(varName("error"),
                                    String.format("Algorithm mismatch: found [%s], expected [%s]",
                                                  foundAlgorithm, requiredAlgorithm));
                return ExecutionResult.ABORT;
            }
        }
    }
    catch (Exception e) {
        msgCtxt.setVariable(varName("error"), "Exception " + e.toString());
        msgCtxt.setVariable(varName("stacktrace"), ExceptionUtils.getStackTrace(e));
        return ExecutionResult.ABORT;
    }
    return ExecutionResult.SUCCESS;
}
 
Example #27
Source File: EncryptionFactory.java    From git-as-svn with GNU General Public License v2.0 4 votes vote down vote up
@NotNull
JsonWebEncryption create();
 
Example #28
Source File: WebServer.java    From git-as-svn with GNU General Public License v2.0 4 votes vote down vote up
@NotNull
public JsonWebEncryption createEncryption() {
  return tokenFactory.create();
}
 
Example #29
Source File: TokenHelperTest.java    From git-as-svn with GNU General Public License v2.0 4 votes vote down vote up
@NotNull
private JsonWebEncryption createToken(@NotNull String secret) {
  return new EncryptionFactoryAes(secret).create();
}
 
Example #30
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);
    }

}