org.jose4j.keys.HmacKey Java Examples

The following examples show how to use org.jose4j.keys.HmacKey. 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: TokenGenerator.java    From rufus with MIT License 6 votes vote down vote up
public String generateToken(String subject) {
    final JwtClaims claims = new JwtClaims();
    claims.setSubject(subject);
    claims.setExpirationTimeMinutesInTheFuture(TOKEN_EXPIRATION_IN_MINUTES);

    final JsonWebSignature jws = new JsonWebSignature();
    jws.setPayload(claims.toJson());
    jws.setAlgorithmHeaderValue(HMAC_SHA256);
    jws.setKey(new HmacKey(tokenSecret));
    jws.setDoKeyValidation(false); //relaxes hmac key length restrictions

    try {
        return jws.getCompactSerialization();
    } catch (JoseException e) {
        throw new RuntimeException(e);
    }
}
 
Example #2
Source File: JwtAuthProviderTest.java    From dropwizard-auth-jwt with Apache License 2.0 6 votes vote down vote up
protected ContainerRequestFilter getAuthFilter() {

            final JwtConsumer consumer = new JwtConsumerBuilder()
                .setRequireExpirationTime() // the JWT must have an expiration time
                .setAllowedClockSkewInSeconds(30) // allow some leeway in validating time based claims to account for clock skew
                .setRequireSubject() // the JWT must have a subject claim
                .setExpectedIssuer("Issuer") // whom the JWT needs to have been issued by
                .setExpectedAudience("Audience") // whom the JWT needs to have been issued by
                .setVerificationKey(new HmacKey(SECRET_KEY.getBytes(UTF_8))) // verify the signature with the public key
                .setRelaxVerificationKeyValidation() // relaxes key length requirement
                .build();// create the JwtConsumer instance

            return new JwtAuthFilter.Builder<>()
                .setCookieName(COOKIE_NAME)
                .setJwtConsumer(consumer)
                .setPrefix(BEARER_PREFIX)
                .setAuthorizer(AuthUtil.getTestAuthorizer(ADMIN_USER, ADMIN_ROLE))
                .setAuthenticator(AuthUtil.getJWTAuthenticator(ImmutableList.of(ADMIN_USER, ORDINARY_USER)))
                .buildAuthFilter();
        }
 
Example #3
Source File: JwtCachingAuthenticatorTest.java    From dropwizard-auth-jwt with Apache License 2.0 6 votes vote down vote up
private JwtContext tokenTwo() {
    final JwtClaims claims = new JwtClaims();
    claims.setSubject("good-guy-two");
    claims.setIssuer("Issuer");
    claims.setAudience("Audience");

    final JsonWebSignature jws = new JsonWebSignature();
    jws.setPayload(claims.toJson());
    jws.setAlgorithmHeaderValue(AlgorithmIdentifiers.HMAC_SHA512);
    jws.setKey(new HmacKey(SECRET.getBytes(UTF_8)));
    jws.setDoKeyValidation(false);

    try {
        return consumer.process(jws.getCompactSerialization());
    }
    catch (Exception e) { throw Throwables.propagate(e); }
}
 
Example #4
Source File: JwtCachingAuthenticatorTest.java    From dropwizard-auth-jwt with Apache License 2.0 6 votes vote down vote up
private JwtContext tokenOne() {
    final JwtClaims claims = new JwtClaims();
    claims.setSubject("good-guy");
    claims.setIssuer("Issuer");
    claims.setAudience("Audience");

    final JsonWebSignature jws = new JsonWebSignature();
    jws.setPayload(claims.toJson());
    jws.setAlgorithmHeaderValue(AlgorithmIdentifiers.HMAC_SHA512);
    jws.setKey(new HmacKey(SECRET.getBytes(UTF_8)));
    jws.setDoKeyValidation(false);

    try {
        return consumer.process(jws.getCompactSerialization());
    }
    catch (Exception e) { throw Throwables.propagate(e); }
}
 
Example #5
Source File: SecuredResource.java    From dropwizard-auth-jwt with Apache License 2.0 6 votes vote down vote up
@GET
@Path("/generate-valid-token")
public Map<String, String> generateValidToken() {
    final JwtClaims claims = new JwtClaims();
    claims.setSubject("good-guy");
    claims.setExpirationTimeMinutesInTheFuture(30);

    final JsonWebSignature jws = new JsonWebSignature();
    jws.setPayload(claims.toJson());
    jws.setAlgorithmHeaderValue(HMAC_SHA256);
    jws.setKey(new HmacKey(tokenSecret));

    try {
        return singletonMap("token", jws.getCompactSerialization());
    }
    catch (JoseException e) { throw Throwables.propagate(e); }
}
 
Example #6
Source File: SecuredResource.java    From dropwizard-auth-jwt with Apache License 2.0 6 votes vote down vote up
@GET
@Path("/generate-expired-token")
public Map<String, String> generateExpiredToken() {
    final JwtClaims claims = new JwtClaims();
    claims.setExpirationTimeMinutesInTheFuture(-20);
    claims.setSubject("good-guy");

    final JsonWebSignature jws = new JsonWebSignature();
    jws.setPayload(claims.toJson());
    jws.setAlgorithmHeaderValue(HMAC_SHA256);
    jws.setKey(new HmacKey(tokenSecret));

    try {
        return singletonMap("token", jws.getCompactSerialization());
    }
    catch (JoseException e) { throw Throwables.propagate(e); }
}
 
Example #7
Source File: OctetSequenceJsonWebKeyTest.java    From Jose4j with Apache License 2.0 6 votes vote down vote up
@Test
public void testExampleFromJws() throws Exception
{
    String base64UrlKey = "AyM1SysPpbyDfgZld3umj1qzKObwVMkoqQ-EstJQLr_T-1qS0gZH75aKtMN3Yj0iPS4hcgUuTwjAzZr1Z9CAow";
    String jwkJson ="{\"kty\":\"oct\",\n"+" \"k\":\""+base64UrlKey+"\"\n"+"}";
    JsonWebKey parsedKey = JsonWebKey.Factory.newJwk(jwkJson);
    assertEquals(OctetSequenceJsonWebKey.class, parsedKey.getClass());

    // these octets are from an earlier draft version (pre -12 I think) before JWKs were
    // used to encode the example keys. makes for a nice test though
    int[]  keyInts = {3, 35, 53, 75, 43, 15, 165, 188, 131, 126, 6, 101, 119, 123, 166,
                       143, 90, 179, 40, 230, 240, 84, 201, 40, 169, 15, 132, 178, 210, 80,
                       46, 191, 211, 251, 90, 146, 210, 6, 71, 239, 150, 138, 180, 195, 119,
                       98, 61, 34, 61, 46, 33, 114, 5, 46, 79, 8, 192, 205, 154, 245, 103,
                       208, 128, 163};
    byte[] keyBytes = ByteUtil.convertUnsignedToSignedTwosComp(keyInts);
    assertTrue(Arrays.equals(keyBytes, parsedKey.getKey().getEncoded()));

    JsonWebKey jwk = JsonWebKey.Factory.newJwk(new HmacKey(keyBytes));

    assertEquals(OctetSequenceJsonWebKey.KEY_TYPE, jwk.getKeyType());
    assertTrue(jwk.toJson().contains(base64UrlKey));
    assertTrue(jwk.toJson(INCLUDE_PRIVATE).contains(base64UrlKey));
    assertTrue(jwk.toJson(INCLUDE_SYMMETRIC).contains(base64UrlKey));
    assertFalse(jwk.toJson(PUBLIC_ONLY).contains(base64UrlKey));
}
 
Example #8
Source File: JwtAuthApplication.java    From dropwizard-auth-jwt with Apache License 2.0 6 votes vote down vote up
@Override
public void run(MyConfiguration configuration, Environment environment) throws Exception {
    final byte[] key = configuration.getJwtTokenSecret();

    final JwtConsumer consumer = new JwtConsumerBuilder()
        .setAllowedClockSkewInSeconds(30) // allow some leeway in validating time based claims to account for clock skew
        .setRequireExpirationTime() // the JWT must have an expiration time
        .setRequireSubject() // the JWT must have a subject claim
        .setVerificationKey(new HmacKey(key)) // verify the signature with the public key
        .setRelaxVerificationKeyValidation() // relaxes key length requirement
        .build(); // create the JwtConsumer instance

    environment.jersey().register(new AuthDynamicFeature(
        new JwtAuthFilter.Builder<MyUser>()
            .setJwtConsumer(consumer)
            .setRealm("realm")
            .setPrefix("Bearer")
            .setAuthenticator(new ExampleAuthenticator())
            .buildAuthFilter()));

    environment.jersey().register(new AuthValueFactoryProvider.Binder<>(Principal.class));
    environment.jersey().register(RolesAllowedDynamicFeature.class);
    environment.jersey().register(new SecuredResource(configuration.getJwtTokenSecret()));
}
 
Example #9
Source File: RsaUsingShaTest.java    From Jose4j with Apache License 2.0 6 votes vote down vote up
public void testBadKeys() throws JoseException
{
    RsaKeyUtil keyUtil = new RsaKeyUtil();

    KeyPair pair = keyUtil.generateKeyPair(1024);
    PublicKey pub = pair.getPublic();
    PrivateKey priv = pair.getPrivate();

    String cs256 = "eyJhbGciOiJSUzI1NiJ9.UEFZTE9BRCEhIQ.ln8y7TlxyR0jLemqdVybaWYmcS2nIseDEqKNJ1J-mM6TXRWjfFKsJr1kzBgh1nKHbVT6q_cgSoPLsb-9WGvpUMkt7N0NxqT2Vffcz_2HMwKvWDJZSjbuj6_XHSJye7gqySHiI2gOggSaYyIqnua-_kOmVGmgncrzwm2YRPgwLXAl9zB0GNul7lNGDvs193WbgOJ-rKGj515NBfqb7cV2VjQg7vsrnzIWT8FKcrQ5TYNXMrybzK5Q_1BNIxOVlrTsdh_pcUNiJvKKgC3_5PBHkhaJrJlxfwmi77YW8ezwXpFKdzbh8cKKzO0ZhamOOJns99HPPot4jr26JCERzBVF3g";
    String cs384 = "eyJhbGciOiJSUzM4NCJ9.UEFZTE9BRCEhIQ.E27QWhxodHU2vB-C3eKr4SQR8YF1jptmDrw7LRtQF1105bUk_WQqI8dCZcJDBsHdJ11O7JEmnRPJLiZd50eFnzcvZsAN5gh7q2eNnxCPuXjH2MoyRlIt6-8aSs-Es0l66Sz4slyOGjqRBRBqHcr7bu6gjo7mBh3XzS8ORnu5zn9Gj5XWr3emX5vwTq66UCfkyf6a2aa4knmYbGW0JiELVWU4rU2UhY5NjhxDW4omlOGiLpNhaX3LAgvA5nvNLi8HFlhVG8-GO4malIjj6rFdpwpZXm3G-sMbpWCcNyu3DUxRDKgjIWjX2SpGLqgXYZEMcAjmF2CA3tsxy43aUalMYQ";
    String cs512 = "eyJhbGciOiJSUzUxMiJ9.UEFZTE9BRCEhIQ.d7n7w-Ndg1-zRrAAQ3kgP_3vg70M5YcPS4eVrGTgD3UILRnMz5rBQh4k42yTVC53K-pmA6ZpphVtlC0lI7j2ViOM9ObC-dR_vOCN0_X7wo3D8qY5KJUDacMpDb_YkWtc5aUpaLilCe7770vNuOU6GK4hXkbTALJuug1V87QVn-xKDHAGMx_b2UgkzybbnribIAeMoqsgg5P9hCSu63xd8OxagbMzPC46ovr5IvTAhIJuONYeGQaOSdOMFFvuZzsZVmdwTQfC9zv-oC3vIF3BcSd1y_8b7CNlFw2NdIf0G3whEnrZgIYofKjZ3QkrIMRGzEF4H3u3KxVwdgpc1OhVSQ";
    for (String cs : new String[] {cs256, cs384, cs512})
    {
        JwsTestSupport.testBadKeyOnVerify(cs, pub);
        JwsTestSupport.testBadKeyOnVerify(cs, priv);
        JwsTestSupport.testBadKeyOnVerify(cs, ExampleRsaKeyFromJws.PRIVATE_KEY);
        JwsTestSupport.testBadKeyOnVerify(cs, null);
        JwsTestSupport.testBadKeyOnVerify(cs, new HmacKey(new byte[2048]));
        JwsTestSupport.testBadKeyOnVerify(cs, ExampleEcKeysFromJws.PUBLIC_256);
        JwsTestSupport.testBadKeyOnVerify(cs, ExampleEcKeysFromJws.PUBLIC_521);
        JwsTestSupport.testBadKeyOnVerify(cs, ExampleEcKeysFromJws.PRIVATE_256);
        JwsTestSupport.testBadKeyOnVerify(cs, ExampleEcKeysFromJws.PRIVATE_521);
    }
}
 
Example #10
Source File: PublicKeyAsHmacKeyTest.java    From Jose4j with Apache License 2.0 6 votes vote down vote up
@Test
public void tryPubKeyAsHmacTrickWithEcBC1() throws Exception
{
    JceProviderTestSupport support = new JceProviderTestSupport();
    support.setUseBouncyCastleRegardlessOfAlgs(true);
    support.runWithBouncyCastleProviderIfNeeded(new JceProviderTestSupport.RunnableTest()
    {
        @Override
        public void runTest() throws Exception
        {
            JsonWebSignature jws = new JsonWebSignature();
            jws.setAlgorithmHeaderValue(AlgorithmIdentifiers.HMAC_SHA256);
            jws.setPayload("scrupulous undercut");
            jws.setKey(new HmacKey(ExampleEcKeysFromJws.PUBLIC_256.getEncoded()));
            verify(ExampleEcKeysFromJws.PUBLIC_256, jws.getCompactSerialization(), false);

        }
    });
}
 
Example #11
Source File: PublicKeyAsHmacKeyTest.java    From Jose4j with Apache License 2.0 6 votes vote down vote up
@Test
public void tryPubKeyAsHmacTrickWithRsaBC2() throws Exception
{
    JceProviderTestSupport support = new JceProviderTestSupport();
    support.setUseBouncyCastleRegardlessOfAlgs(true);
    support.runWithBouncyCastleProviderIfNeeded(new JceProviderTestSupport.RunnableTest()
    {
        @Override
        public void runTest() throws Exception
        {
            JsonWebSignature jws = new JsonWebSignature();
            jws.setAlgorithmHeaderValue(AlgorithmIdentifiers.HMAC_SHA256);
            jws.setPayload("http://watchout4snakes.com/wo4snakes/Random/RandomPhrase");
            jws.setKey(new HmacKey(ExampleRsaKeyFromJws.PUBLIC_KEY.getEncoded()));
            verify(ExampleRsaKeyFromJws.PUBLIC_KEY, jws.getCompactSerialization(), false);
        }
    });
}
 
Example #12
Source File: HmacShaTest.java    From Jose4j with Apache License 2.0 6 votes vote down vote up
public void testVailidateKeySwitch() throws JoseException
{
    JsonWebSignature jws = new JsonWebSignature();
    jws.setPayload("whatever");
    jws.setAlgorithmHeaderValue(AlgorithmIdentifiers.HMAC_SHA256);
    jws.setKey(new HmacKey(new byte[] {1,2,5,-9,99,-99,0,40,21}));
    jws.setDoKeyValidation(false);
    String cs = jws.getCompactSerialization();
    assertNotNull(cs);

    try
    {
        jws.setDoKeyValidation(true);
        jws.getCompactSerialization();
        Assert.fail("Should have failed with some kind of invalid key message but got " + cs);
    }
    catch (InvalidKeyException e)
    {
        log.debug("Expected something like this: {}", e.toString());
    }
}
 
Example #13
Source File: JwtAuthProviderTest.java    From dropwizard-auth-jwt with Apache License 2.0 5 votes vote down vote up
private String toToken(byte[] key, JwtClaims claims) {
    final JsonWebSignature jws = new JsonWebSignature();
    jws.setPayload(claims.toJson());
    jws.setAlgorithmHeaderValue(HMAC_SHA512);
    jws.setKey(new HmacKey(key));
    jws.setDoKeyValidation(false);

    try {
        return jws.getCompactSerialization();
    }
    catch (JoseException e) { throw Throwables.propagate(e); }
}
 
Example #14
Source File: TokenBuilder.java    From uyuni with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Create a cryptographic key from the given secret.
 *
 * @param secret the secret to use for generating the key in hex
 *               string format
 * @return the key
 */
public static Key getKeyForSecret(String secret) {
    try {
        byte[] bytes = Hex.decodeHex(secret.toCharArray());
        return new HmacKey(bytes);
    }
    catch (DecoderException e) {
        throw new IllegalArgumentException(e);
    }
}
 
Example #15
Source File: Operation.java    From pingid-api-playground with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
private String buildRequestToken(JSONObject requestBody) {
	
	JSONObject requestHeader = buildRequestHeader();
	
	JSONObject payload = new JSONObject();
	payload.put("reqHeader", requestHeader);
	payload.put("reqBody", requestBody);
	
	JsonWebSignature jws = new JsonWebSignature();

	jws.setAlgorithmHeaderValue(AlgorithmIdentifiers.HMAC_SHA256);
	jws.setHeader("orgAlias", this.orgAlias);
	jws.setHeader("token", this.token);
	
	jws.setPayload(payload.toJSONString());
	
    // Set the verification key
    HmacKey key = new HmacKey(Base64.decode(this.useBase64Key));
    jws.setKey(key);
	
	String jwsCompactSerialization = null;
	try {
		jwsCompactSerialization = jws.getCompactSerialization();
	} catch (JoseException e) {
		e.printStackTrace();
	}
	
	this.requestToken = jwsCompactSerialization;
			
	return jwsCompactSerialization;
}
 
Example #16
Source File: PublicKeyAsHmacKeyTest.java    From Jose4j with Apache License 2.0 5 votes vote down vote up
@Test
public void tryPubKeyAsHmacTrick() throws JoseException
{
    JsonWebSignature jws = new JsonWebSignature();
    jws.setAlgorithmHeaderValue(AlgorithmIdentifiers.RSA_USING_SHA256);
    jws.setPayload("tardier toothache");
    jws.setKey(ExampleRsaKeyFromJws.PRIVATE_KEY);
    verify(ExampleRsaKeyFromJws.PUBLIC_KEY, jws.getCompactSerialization(), true);

    jws = new JsonWebSignature();
    jws.setAlgorithmHeaderValue(AlgorithmIdentifiers.HMAC_SHA256);
    jws.setPayload("http://watchout4snakes.com/wo4snakes/Random/RandomPhrase");
    jws.setKey(new HmacKey(ExampleRsaKeyFromJws.PUBLIC_KEY.getEncoded()));
    verify(ExampleRsaKeyFromJws.PUBLIC_KEY, jws.getCompactSerialization(), false);

    jws = new JsonWebSignature();
    jws.setAlgorithmHeaderValue(AlgorithmIdentifiers.HMAC_SHA256);
    jws.setPayload("salty slop");
    jws.setKey(new SecretKeySpec(ExampleRsaKeyFromJws.PUBLIC_KEY.getEncoded(), "algorithm"));
    verify(ExampleRsaKeyFromJws.PUBLIC_KEY, jws.getCompactSerialization(), false);

    jws = new JsonWebSignature();
    jws.setAlgorithmHeaderValue(AlgorithmIdentifiers.ECDSA_USING_P256_CURVE_AND_SHA256);
    jws.setPayload("flammable overture");
    jws.setKey(ExampleEcKeysFromJws.PRIVATE_256);
    verify(ExampleEcKeysFromJws.PUBLIC_256, jws.getCompactSerialization(), true);

    jws = new JsonWebSignature();
    jws.setAlgorithmHeaderValue(AlgorithmIdentifiers.HMAC_SHA256);
    jws.setPayload("scrupulous undercut");
    jws.setKey(new HmacKey(ExampleEcKeysFromJws.PUBLIC_256.getEncoded()));
    verify(ExampleEcKeysFromJws.PUBLIC_256, jws.getCompactSerialization(), false);

    jws = new JsonWebSignature();
    jws.setAlgorithmHeaderValue(AlgorithmIdentifiers.HMAC_SHA256);
    jws.setPayload("menial predestination");
    jws.setKey(new SecretKeySpec(ExampleEcKeysFromJws.PUBLIC_256.getEncoded(), ""));
    verify(ExampleEcKeysFromJws.PUBLIC_256, jws.getCompactSerialization(), false);
}
 
Example #17
Source File: ChangingKeyTest.java    From Jose4j with Apache License 2.0 5 votes vote down vote up
@Test
public void testOnNewKey() throws Exception
{
    JsonWebKey jwk = JsonWebKey.Factory.newJwk("{\"kty\":\"oct\",\"k\":\"9el2Km2s5LHVQqUCWIdvwMsclQqQc6CwObMnCpCC8jY\"}");

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

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

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

    jws.setKey(null);
    try
    {
        jws.verifySignature();
    }
    catch (JoseException e)
    {
        // expected
    }
}
 
Example #18
Source File: SharedResourceTest.java    From eplmp with Eclipse Public License 1.0 5 votes vote down vote up
@Before
public void setup() throws Exception {
    initMocks(this);
    sharedResource.init();
    Key key = new HmacKey("verySecretPhrase".getBytes("UTF-8"));
    Mockito.when(authConfig.getJWTKey()).thenReturn(key);
}
 
Example #19
Source File: AccountResourceTest.java    From eplmp with Eclipse Public License 1.0 5 votes vote down vote up
@Test
public void createAccountTest() throws ApplicationException, IOException, ServletException {
    Key key = new HmacKey("verySecretPhrase".getBytes("UTF-8"));
    Mockito.when(authConfig.getJWTKey()).thenReturn(key);

    HttpServletRequest mockedRequest = Mockito.mock(HttpServletRequest.class);
    HttpServletResponse mockedResponse = Mockito.mock(HttpServletResponse.class);
    HttpSession mockedSession = Mockito.mock(HttpSession.class);
    Mockito.when(mockedRequest.getSession()).thenReturn(mockedSession);

    AccountDTO accountDTO = new AccountDTO();
    Account account = new Account();

    Mockito.when(accountManager.createAccount(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(),
            Matchers.anyString(), Matchers.anyString(), Matchers.anyString()))
            .thenReturn(account);

    Response res = accountResource.createAccount(mockedRequest, mockedResponse, accountDTO);
    Assert.assertEquals(Response.Status.ACCEPTED.getStatusCode(), res.getStatus());

    account.setEnabled(true);
    res = accountResource.createAccount(mockedRequest, mockedResponse, accountDTO);
    Assert.assertEquals(Response.Status.OK.getStatusCode(), res.getStatus());


    Mockito.when(authConfig.isJwtEnabled()).thenReturn(true);
    res = accountResource.createAccount(mockedRequest, mockedResponse, accountDTO);
    Assert.assertNotNull(res.getHeaderString("jwt"));

    Mockito.when(authConfig.isJwtEnabled()).thenReturn(false);
    res = accountResource.createAccount(mockedRequest, mockedResponse, accountDTO);
    Assert.assertNull(res.getHeaderString("jwt"));


    Mockito.when(mockedRequest.authenticate(mockedResponse))
            .thenThrow(new IOException("Mocked exception"));
    res = accountResource.createAccount(mockedRequest, mockedResponse, accountDTO);
    Assert.assertEquals(Response.Status.FORBIDDEN.getStatusCode(), res.getStatus());

}
 
Example #20
Source File: AuthConfig.java    From eplmp with Eclipse Public License 1.0 5 votes vote down vote up
public Key getJWTKey() {
    try {
        String secret = properties.getProperty("jwt.key");
        if (null != secret && !secret.isEmpty()) {
            return new HmacKey(secret.getBytes("UTF-8"));
        }
    }
    catch (UnsupportedEncodingException e) {
        LOGGER.log(Level.SEVERE, "Cannot create JWT key", e);
    }
    return defaultKey;
}
 
Example #21
Source File: HmacShaTest.java    From Jose4j with Apache License 2.0 4 votes vote down vote up
public void testMinKeySize384ForVerify() throws JoseException
{
    String compactSerialization = "eyJhbGciOiJIUzM4NCJ9.eyJtZWgiOiJtZWgifQ.fptKQJmGN3fBP_FiQzdAGdmx-Q5iWjQvJrLfdmFnebxbQuzOmzejBrzYh4MyS01a";
    Key key = new HmacKey(new byte[47]);
    JwsTestSupport.testBadKeyOnVerify(compactSerialization, key);
}
 
Example #22
Source File: HmacShaTest.java    From Jose4j with Apache License 2.0 4 votes vote down vote up
public void testMinKeySize512ForVerify() throws JoseException
{
    String compactSerialization = "eyJhbGciOiJIUzUxMiJ9.eyJtZWgiOiJtZWh2YWx1ZSJ9.NeB669dYkPmqgLqgd_sVqwIfCvb4XN-K67gpMJR93wfw_DylpxB1ell2opHM-E5P9jNKE2GYxTxwcI68Z2CTxw";
    Key key = new HmacKey(new byte[63]);
    JwsTestSupport.testBadKeyOnVerify(compactSerialization, key);
}
 
Example #23
Source File: HmacShaTest.java    From Jose4j with Apache License 2.0 4 votes vote down vote up
public void testMinKeySize256ForVerify() throws JoseException
{
    String compactSerialization = "eyJhbGciOiJIUzI1NiJ9.c29tZSBjb250ZW50IHRoYXQgaXMgdGhlIHBheWxvYWQ.qGO7O7W2ECVl6uO7lfsXDgEF-EUEti0i-a_AimulIRA";
    Key key = new HmacKey(new byte[31]);
    JwsTestSupport.testBadKeyOnVerify(compactSerialization, key);
}
 
Example #24
Source File: HmacShaTest.java    From Jose4j with Apache License 2.0 4 votes vote down vote up
public void testMinKeySize512ForSign()
{
    JwsTestSupport.testBadKeyOnSign(AlgorithmIdentifiers.HMAC_SHA512, new HmacKey(new byte[63]));
}
 
Example #25
Source File: HmacShaTest.java    From Jose4j with Apache License 2.0 4 votes vote down vote up
public void testMinKeySize384ForSign()
{
    JwsTestSupport.testBadKeyOnSign(AlgorithmIdentifiers.HMAC_SHA384, new HmacKey(new byte[47]));
}
 
Example #26
Source File: HmacShaTest.java    From Jose4j with Apache License 2.0 4 votes vote down vote up
public void testMinKeySize256ForSign2()
{
    JwsTestSupport.testBadKeyOnSign(AlgorithmIdentifiers.HMAC_SHA256, new HmacKey(new byte[31]));
}
 
Example #27
Source File: KeyGenerators.java    From datamill with ISC License 4 votes vote down vote up
public static void generate() throws Exception {
    byte[] bytes = ByteUtil.randomBytes(ByteUtil.byteLength(512));
    OctetSequenceJsonWebKey key = new OctetSequenceJsonWebKey(new HmacKey(bytes));
    key.setKeyId("k" + System.currentTimeMillis());
    System.out.println(new JsonWebKeySet(key).toJson(JsonWebKey.OutputControlLevel.INCLUDE_SYMMETRIC));
}
 
Example #28
Source File: HmacShaTest.java    From Jose4j with Apache License 2.0 4 votes vote down vote up
public void testMinKeySize256ForSign()
{
    JwsTestSupport.testBadKeyOnSign(AlgorithmIdentifiers.HMAC_SHA256, new HmacKey(new byte[1]));
}
 
Example #29
Source File: PasswordBasedKeyDerivationFunction2.java    From Jose4j with Apache License 2.0 4 votes vote down vote up
public byte[] derive(byte[] password, byte[] salt, int iterationCount, int dkLen, String provider) throws JoseException
{
    Mac prf = MacUtil.getInitializedMac(hmacAlgorithm, new HmacKey(password), provider);
    int hLen = prf.getMacLength();

    //  1. If dkLen > (2^32 - 1) * hLen, output "derived key too long" and
    //     stop.
    long maxDerivedKeyLength = 4294967295L; // value of (long) Math.pow(2, 32) - 1;
    if (dkLen > maxDerivedKeyLength)
    {
        throw new UncheckedJoseException("derived key too long " + dkLen);
    }

    //  2. Let l be the number of hLen-octet blocks in the derived key,
    //     rounding up, and let r be the number of octets in the last
    //     block:
    //
    //               l = CEIL (dkLen / hLen) ,
    //               r = dkLen - (l - 1) * hLen .
    //
    //     Here, CEIL (x) is the "ceiling" function, i.e. the smallest
    //     integer greater than, or equal to, x.
    int l = (int) Math.ceil((double) dkLen / (double) hLen);
    int r = dkLen - (l - 1) * hLen;

    //  3. For each block of the derived key apply the function F defined
    //     below to the password P, the salt S, the iteration count c, and
    //     the block index to compute the block:
    //
    //               T_1 = F (P, S, c, 1) ,
    //               T_2 = F (P, S, c, 2) ,
    //               ...
    //               T_l = F (P, S, c, l) ,
    //
    //     where the function F is defined as the exclusive-or sum of the
    //     first c iterates of the underlying pseudorandom function PRF
    //     applied to the password P and the concatenation of the salt S
    //     and the block index i:
    //
    //               F (P, S, c, i) = U_1 \xor U_2 \xor ... \xor U_c
    //
    //     where
    //
    //               U_1 = PRF (P, S || INT (i)) ,
    //               U_2 = PRF (P, U_1) ,
    //               ...
    //               U_c = PRF (P, U_{c-1}) .
    //
    //     Here, INT (i) is a four-octet encoding of the integer i, most
    //     significant octet first.

    //  4. Concatenate the blocks and extract the first dkLen octets to
    //     produce a derived key DK:
    //
    //               DK = T_1 || T_2 ||  ...  || T_l<0..r-1>
    //
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    for (int i = 0; i < l; i++)
    {
        byte[] block = f(salt, iterationCount, i + 1, prf);
        if (i == (l - 1))
        {
            block = ByteUtil.subArray(block, 0, r);
        }
        byteArrayOutputStream.write(block, 0, block.length);
    }

    //  5. Output the derived key DK.
    return byteArrayOutputStream.toByteArray();
}
 
Example #30
Source File: AccountResourceTest.java    From eplmp with Eclipse Public License 1.0 4 votes vote down vote up
@Test
public void updateAccountTest() throws ApplicationException, UnsupportedEncodingException {

    Key key = new HmacKey("verySecretPhrase".getBytes("UTF-8"));
    UserGroupMapping groupMapping = new UserGroupMapping("FooBar", UserGroupMapping.REGULAR_USER_ROLE_ID);
    String authToken = JWTokenFactory.createAuthToken(key, groupMapping);
    Account account = new Account("FooBar");
    Mockito.when(authConfig.getJWTKey()).thenReturn(key);

    Mockito.when(accountManager.updateAccount(Matchers.anyString(), Matchers.anyString(), Matchers.anyString(),
            Matchers.anyString(), Matchers.anyString())).thenReturn(account);

    AccountDTO accountDTO = new AccountDTO();
    accountDTO.setLogin(account.getLogin());
    Response res = accountResource.updateAccount(null, accountDTO);
    Assert.assertEquals(Response.Status.FORBIDDEN.getStatusCode(), res.getStatus());

    accountDTO.setPassword("");
    res = accountResource.updateAccount(null, accountDTO);
    Assert.assertEquals(Response.Status.FORBIDDEN.getStatusCode(), res.getStatus());

    res = accountResource.updateAccount("WithoutBearer " + authToken, accountDTO);
    Assert.assertEquals(Response.Status.FORBIDDEN.getStatusCode(), res.getStatus());

    res = accountResource.updateAccount("Bearer " + authToken, accountDTO);
    Assert.assertEquals(Response.Status.OK.getStatusCode(), res.getStatus());

    accountDTO.setPassword("SomePass");
    Mockito.when(accountManager.authenticateAccount(Matchers.anyString(), Matchers.anyString()))
            .thenReturn(null);
    try {
        accountResource.updateAccount(null, accountDTO);
        Assert.fail("Should have thrown");
    } catch (NotAllowedException e) {
        Assert.assertNotNull(e.getMessage());
    }

    Mockito.when(accountManager.authenticateAccount(Matchers.anyString(), Matchers.anyString()))
            .thenReturn(account);
    res = accountResource.updateAccount(null, accountDTO);

    Assert.assertEquals(Response.Status.OK.getStatusCode(), res.getStatus());

    Mockito.when(contextManager.isCallerInRole(UserGroupMapping.ADMIN_ROLE_ID)).thenReturn(true);
    res = accountResource.updateAccount(null, accountDTO);
    Object entity = res.getEntity();
    Assert.assertTrue(((AccountDTO) entity).isAdmin());
}