当前位置: 首页>>代码示例>>Java>>正文


Java HmacKey类代码示例

本文整理汇总了Java中org.jose4j.keys.HmacKey的典型用法代码示例。如果您正苦于以下问题:Java HmacKey类的具体用法?Java HmacKey怎么用?Java HmacKey使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


HmacKey类属于org.jose4j.keys包,在下文中一共展示了HmacKey类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: generateToken

import org.jose4j.keys.HmacKey; //导入依赖的package包/类
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);
    }
}
 
开发者ID:jtanza,项目名称:rufus,代码行数:18,代码来源:TokenGenerator.java

示例2: testExampleFromJws

import org.jose4j.keys.HmacKey; //导入依赖的package包/类
@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));
}
 
开发者ID:RbkGh,项目名称:Jose4j,代码行数:27,代码来源:OctetSequenceJsonWebKeyTest.java

示例3: testBadKeys

import org.jose4j.keys.HmacKey; //导入依赖的package包/类
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);
    }
}
 
开发者ID:RbkGh,项目名称:Jose4j,代码行数:25,代码来源:RsaUsingShaTest.java

示例4: testVailidateKeySwitch

import org.jose4j.keys.HmacKey; //导入依赖的package包/类
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());
    }
}
 
开发者ID:RbkGh,项目名称:Jose4j,代码行数:22,代码来源:HmacShaTest.java

示例5: tryPubKeyAsHmacTrickWithRsaBC2

import org.jose4j.keys.HmacKey; //导入依赖的package包/类
@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);
        }
    });
}
 
开发者ID:RbkGh,项目名称:Jose4j,代码行数:19,代码来源:PublicKeyAsHmacKeyTest.java

示例6: tryPubKeyAsHmacTrickWithEcBC1

import org.jose4j.keys.HmacKey; //导入依赖的package包/类
@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);

        }
    });
}
 
开发者ID:RbkGh,项目名称:Jose4j,代码行数:20,代码来源:PublicKeyAsHmacKeyTest.java

示例7: verifyToken

import org.jose4j.keys.HmacKey; //导入依赖的package包/类
public static User verifyToken(String data) {
	JwtConsumer jwtConsumer = new JwtConsumerBuilder()
			.setRequireExpirationTime() // the JWT must have an expiration time
			.setMaxFutureValidityInMinutes(60*24) // but the  expiration time can't be too crazy
			.setAllowedClockSkewInSeconds(30) // allow some leeway in validating time based claims to account for clock skew
			.setRequireSubject() // the JWT must have a subject claim
			.setExpectedIssuer("server") // whom the JWT needs to have been issued by
			.setExpectedAudience("client") // to whom the JWT is intended for
			.setVerificationKey(new HmacKey(secret.getBytes())) // verify the signature with the public key
			.build(); // create the JwtConsumer instance

	try
	{
		//  Validate the JWT and process it to the Claims
		JwtClaims jwtClaims = jwtConsumer.processToClaims(data);
		ObjectMapper mapper = new ObjectMapper();
		String json = (String) jwtClaims.getClaimValue("userData");
		byte[] bytes = json.getBytes("UTF-8");
		return mapper.readValue(bytes, User.class);
	}
	catch (Exception e) {
		return null;
	}

}
 
开发者ID:proyectos-ce,项目名称:moncha-server,代码行数:26,代码来源:TokenProvider.java

示例8: readToken

import org.jose4j.keys.HmacKey; //导入依赖的package包/类
public Optional<TokenDTO> readToken(String token) {

	try {
	    Key key = new HmacKey(secret.getBytes("UTF-8"));

	    JwtConsumer jwtConsumer = new JwtConsumerBuilder().setVerificationKey(key).build();

	    JwtClaims jwtClaims = jwtConsumer.processToClaims(token);
	    Map<String, Object> claimsMap = jwtClaims.getClaimsMap();

	    TokenDTO data = new TokenDTO();
	    data.setEmail((String) claimsMap.get(EMAIL_KEY));
	    data.setIssuer((String) claimsMap.get(ReservedClaimNames.ISSUER));
	    data.setSubject((String) claimsMap.get(ReservedClaimNames.SUBJECT));

	    return Optional.of(data);

	} catch (Exception e) {
	    return Optional.empty();
	}
    }
 
开发者ID:tomacla,项目名称:auth-token,代码行数:22,代码来源:ReadOnlyTokenManager.java

示例9: JWTVerifier

import org.jose4j.keys.HmacKey; //导入依赖的package包/类
public JWTVerifier(final String secret, final String issuer, final String audience)
{
	final JwtConsumerBuilder builder = new JwtConsumerBuilder();

	if (StringUtils.isNotBlank(audience))
		builder.setExpectedAudience(audience);

	if (StringUtils.isNotBlank(issuer))
		builder.setExpectedIssuer(issuer);

	builder.setVerificationKey(new HmacKey(secret.getBytes(StandardCharsets.UTF_8)));
	builder.setAllowedClockSkewInSeconds(60);
	builder.setRelaxVerificationKeyValidation(); // Allow HMAC keys < 256 bits

	consumer = builder.build();
}
 
开发者ID:petergeneric,项目名称:stdlib,代码行数:17,代码来源:JWTVerifier.java

示例10: toToken

import org.jose4j.keys.HmacKey; //导入依赖的package包/类
private static String toToken(byte[] key, JwtClaims claims) {
    final JsonWebSignature jws = new JsonWebSignature();
    jws.setPayload(claims.toJson());
    jws.setAlgorithmHeaderValue(HMAC_SHA256);
    jws.setKey(new HmacKey(key));
    jws.setDoKeyValidation(false);

    try {
        return jws.getCompactSerialization();
    }
    catch (JoseException e) { throw Throwables.propagate(e); }
}
 
开发者ID:gchq,项目名称:stroom-stats,代码行数:13,代码来源:AuthorizationHelper.java

示例11: getJWTKey

import org.jose4j.keys.HmacKey; //导入依赖的package包/类
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;
}
 
开发者ID:polarsys,项目名称:eplmp,代码行数:13,代码来源:AuthConfig.java

示例12: testOnNewKey

import org.jose4j.keys.HmacKey; //导入依赖的package包/类
@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
    }
}
 
开发者ID:RbkGh,项目名称:Jose4j,代码行数:28,代码来源:ChangingKeyTest.java

示例13: tryPubKeyAsHmacTrick

import org.jose4j.keys.HmacKey; //导入依赖的package包/类
@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);
}
 
开发者ID:RbkGh,项目名称:Jose4j,代码行数:40,代码来源:PublicKeyAsHmacKeyTest.java

示例14: buildRequestToken

import org.jose4j.keys.HmacKey; //导入依赖的package包/类
@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("org_alias", 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;
}
 
开发者ID:pingidentity,项目名称:pingid-api-playground,代码行数:33,代码来源:Operation.java

示例15: parseResponse

import org.jose4j.keys.HmacKey; //导入依赖的package包/类
private JSONObject parseResponse() {

		JSONParser parser = new JSONParser();
		JSONObject responsePayloadJSON = null;

		try {

			JsonWebSignature responseJWS = new JsonWebSignature();
			responseJWS.setCompactSerialization(this.responseToken);
			HmacKey key = new HmacKey(Base64.decode(this.useBase64Key));
			responseJWS.setKey(key);
			responsePayloadJSON = (JSONObject)parser.parse(responseJWS.getPayload());

			// workaround for PingID API 4.5 beta
			if (responsePayloadJSON.containsKey("responseBody")) {
				responsePayloadJSON = (JSONObject)responsePayloadJSON.get("responseBody");
			}

		} catch (Exception e) {
			e.printStackTrace();
		}

		if (responsePayloadJSON != null) {
			this.errorId = (long)responsePayloadJSON.get("errorId");
			this.errorMsg = (String)responsePayloadJSON.get("errorMsg");
			this.uniqueMsgId = (String)responsePayloadJSON.get("uniqueMsgId");
			this.clientData = (String)responsePayloadJSON.get("clientData");
		} else {
			this.errorId = 501;
			this.errorMsg = "Could not parse JWS";
			this.uniqueMsgId = "";
			this.clientData = "";
			this.wasSuccessful = false;
		}

		return responsePayloadJSON;
	}
 
开发者ID:pingidentity,项目名称:pingid-api-playground,代码行数:38,代码来源:Operation.java


注:本文中的org.jose4j.keys.HmacKey类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。