com.nimbusds.jose.JWSObject Java Examples

The following examples show how to use com.nimbusds.jose.JWSObject. 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: PacketHandler.java    From BedrockConnect with GNU General Public License v3.0 7 votes vote down vote up
private static boolean validateChainData(JsonNode data) throws Exception {
    ECPublicKey lastKey = null;
    boolean validChain = false;
    for (JsonNode node : data) {
        JWSObject jwt = JWSObject.parse(node.asText());

        if (!validChain) {
            validChain = verifyJwt(jwt, EncryptionUtils.getMojangPublicKey());
        }

        if (lastKey != null) {
            verifyJwt(jwt, lastKey);
        }

        JsonNode payloadNode = Server.JSON_MAPPER.readTree(jwt.getPayload().toString());
        JsonNode ipkNode = payloadNode.get("identityPublicKey");
        Preconditions.checkState(ipkNode != null && ipkNode.getNodeType() == JsonNodeType.STRING, "identityPublicKey node is missing in chain");
        lastKey = EncryptionUtils.generateKey(ipkNode.asText());
    }
    return validChain;
}
 
Example #2
Source File: TokenUtil.java    From peer-os with Apache License 2.0 6 votes vote down vote up
public static boolean verifySignature( String token, String sharedKey )
{
    boolean verifiedSignature = false;

    try
    {
        JWSObject jwsObject = JWSObject.parse( token );
        JWSVerifier verifier = new MACVerifier( sharedKey.getBytes() );
        verifiedSignature = jwsObject.verify( verifier );
    }
    catch ( Exception e )
    {
        LOG.warn( e.getMessage() );
    }

    return verifiedSignature;
}
 
Example #3
Source File: KnoxService.java    From nifi with Apache License 2.0 6 votes vote down vote up
/**
 * Validate the jwt signature.
 *
 * @param jwtToken knox jwt
 * @return whether this jwt signature is valid
 * @throws JOSEException if the jws object couldn't be verified
 */
private boolean validateSignature(final SignedJWT jwtToken) throws JOSEException {
    boolean valid = false;

    // ensure the token is signed
    if (JWSObject.State.SIGNED.equals(jwtToken.getState())) {

        // ensure the signature is present
        if (jwtToken.getSignature() != null) {

            // verify the token
            valid = jwtToken.verify(verifier);
        }
    }

    if (!valid) {
        logger.error("The Knox JWT has an invalid signature.");
    }

    return valid;
}
 
Example #4
Source File: SimpleJWTProcessor.java    From hammock with Apache License 2.0 6 votes vote down vote up
@Override
public JsonObject process(String jwt) throws JWTException {
    String[] parts = jwt.split("\\.");
    if(parts.length == 3) {
        Base64URL first = new Base64URL(parts[0]);
        Base64URL second = new Base64URL(parts[1]);
        Base64URL third = new Base64URL(parts[2]);
        try {
            String rawJwt = new JWSObject(first, second, third).getPayload().toString();
            return Json.createReader(new StringReader(rawJwt)).readObject();
        }
        catch (ParseException e) {
            throw new JWTException("Unable to parse JWT", e);
        }
    }
    else {
        return null;
    }
}
 
Example #5
Source File: MACVerifierExtendedTest.java    From shiro-jwt with MIT License 6 votes vote down vote up
@Test
public void invalidTokenExpirationTime() throws JOSEException, ParseException {
    JWTClaimsSet jwtClaims = getJWTClaimsSet("issuer", "subject", new Date(), new Date(), new Date());

    JWSHeader header = new JWSHeader(JWSAlgorithm.HS256);

    Payload payload = new Payload(jwtClaims.toJSONObject());

    JWSObject jwsObject = new JWSObject(header, payload);

    JWSSigner signer = new MACSigner(sharedKey);
    jwsObject.sign(signer);
    String token = jwsObject.serialize();

    SignedJWT signed = SignedJWT.parse(token);
    JWSVerifier verifier = new MACVerifierExtended(sharedKey, signed.getJWTClaimsSet());
    signed.verify(verifier);

    Assert.assertFalse("Must be invalid", signed.verify(verifier));
}
 
Example #6
Source File: MACVerifierExtendedTest.java    From shiro-jwt with MIT License 6 votes vote down vote up
@Test
public void invalidTokenNotBeforeTime() throws JOSEException, ParseException {
    JWTClaimsSet jwtClaims = getJWTClaimsSet("issuer", "subject", new Date(), new Date(new Date().getTime() + 100000), new Date(new Date().getTime() + 200000));

    JWSHeader header = new JWSHeader(JWSAlgorithm.HS256);

    Payload payload = new Payload(jwtClaims.toJSONObject());

    JWSObject jwsObject = new JWSObject(header, payload);

    JWSSigner signer = new MACSigner(sharedKey);
    jwsObject.sign(signer);
    String token = jwsObject.serialize();

    SignedJWT signed = SignedJWT.parse(token);
    JWSVerifier verifier = new MACVerifierExtended(sharedKey, signed.getJWTClaimsSet());
    signed.verify(verifier);

    Assert.assertFalse("Must be invalid", signed.verify(verifier));
}
 
Example #7
Source File: MACVerifierExtendedTest.java    From shiro-jwt with MIT License 6 votes vote down vote up
@Test
public void validToken() throws JOSEException, ParseException {
    JWTClaimsSet jwtClaims = getJWTClaimsSet("issuer", "subject", new Date(), new Date(), new Date(new Date().getTime() + 100000));

    JWSHeader header = new JWSHeader(JWSAlgorithm.HS256);

    Payload payload = new Payload(jwtClaims.toJSONObject());

    JWSObject jwsObject = new JWSObject(header, payload);

    JWSSigner signer = new MACSigner(sharedKey);
    jwsObject.sign(signer);
    String token = jwsObject.serialize();

    SignedJWT signed = SignedJWT.parse(token);
    JWSVerifier verifier = new MACVerifierExtended(sharedKey, signed.getJWTClaimsSet());
    signed.verify(verifier);

    Assert.assertTrue("Must be valid", signed.verify(verifier));
}
 
Example #8
Source File: JWTOrFormAuthenticationFilter.java    From shiro-jwt with MIT License 6 votes vote down vote up
public JWTAuthenticationToken createToken(String token) {
    try {
        JWSObject jwsObject = JWSObject.parse(token);
        String decrypted = jwsObject.getPayload().toString();
        
        try (JsonReader jr = Json.createReader(new StringReader(decrypted))) {
            JsonObject object = jr.readObject();

            String userId = object.getString("sub", null);
            return new JWTAuthenticationToken(userId, token);
        }

    } catch (ParseException ex) {
        throw new AuthenticationException(ex);
    }

}
 
Example #9
Source File: UserRepository.java    From shiro-jwt with MIT License 6 votes vote down vote up
default String createToken(Object userId) {
    try {
        JWTClaimsSet.Builder builder = new JWTClaimsSet.Builder();

        builder.issuer(getIssuer());
        builder.subject(userId.toString());
        builder.issueTime(new Date());
        builder.notBeforeTime(new Date());
        builder.expirationTime(new Date(new Date().getTime() + getExpirationDate()));
        builder.jwtID(UUID.randomUUID().toString());

        JWTClaimsSet claimsSet = builder.build();
        JWSHeader header = new JWSHeader(JWSAlgorithm.HS256);

        Payload payload = new Payload(claimsSet.toJSONObject());

        JWSObject jwsObject = new JWSObject(header, payload);

        JWSSigner signer = new MACSigner(getSharedKey());
        jwsObject.sign(signer);
        return jwsObject.serialize();
    } catch (JOSEException ex) {
        return null;
    }
}
 
Example #10
Source File: KnoxJwtRealm.java    From zeppelin with Apache License 2.0 6 votes vote down vote up
protected boolean validateSignature(SignedJWT jwtToken) {
  boolean valid = false;
  if (JWSObject.State.SIGNED == jwtToken.getState()) {
    if (jwtToken.getSignature() != null) {
      try {
        RSAPublicKey publicKey = parseRSAPublicKey(publicKeyPath);
        JWSVerifier verifier = new RSASSAVerifier(publicKey);
        if (verifier != null && jwtToken.verify(verifier)) {
          valid = true;
        }
      } catch (Exception e) {
        LOGGER.info("Exception in validateSignature", e);
      }
    }
  }
  return valid;
}
 
Example #11
Source File: JWTAuthenticationHandler.java    From registry with Apache License 2.0 6 votes vote down vote up
/**
 * Verify the signature of the JWT token in this method. This method depends
 * on the public key that was established during init based upon the
 * provisioned public key. Override this method in subclasses in order to
 * customize the signature verification behavior.
 *
 * @param jwtToken the token that contains the signature to be validated
 * @return valid true if signature verifies successfully; false otherwise
 */
protected boolean validateSignature(SignedJWT jwtToken) {
    boolean valid = false;
    if (JWSObject.State.SIGNED == jwtToken.getState()) {
        LOG.debug("JWT token is in a SIGNED state");
        if (jwtToken.getSignature() != null) {
            LOG.debug("JWT token signature is not null");
            try {
                JWSVerifier verifier = new RSASSAVerifier(publicKey);
                if (jwtToken.verify(verifier)) {
                    valid = true;
                    LOG.debug("JWT token has been successfully verified");
                } else {
                    LOG.warn("JWT signature verification failed.");
                }
            } catch (JOSEException je) {
                LOG.warn("Error while validating signature", je);
            }
        }
    }
    return valid;
}
 
Example #12
Source File: TokenUtil.java    From peer-os with Apache License 2.0 6 votes vote down vote up
public static boolean verifyTokenRSA( PublicKey pKey, String token )
{
    try
    {
        Payload pl = new Payload( token );
        JWSObject jwsObject = new JWSObject( new JWSHeader( JWSAlgorithm.RS256 ), pl );
        JWSVerifier verifier = new RSASSAVerifier( ( RSAPublicKey ) pKey );

        return jwsObject.verify( verifier );
    }
    catch ( JOSEException e )
    {
        LOG.warn( "Error verifying RSA token", e.getMessage() );

        return false;
    }
}
 
Example #13
Source File: TokenUtil.java    From peer-os with Apache License 2.0 6 votes vote down vote up
public static String createTokenRSA( PrivateKey privateKey, String claimJson )
{
    try
    {
        JWSSigner signer = new RSASSASigner( ( RSAPrivateKey ) privateKey );

        Payload pl = new Payload( claimJson );
        JWSObject jwsObject = new JWSObject( new JWSHeader( JWSAlgorithm.RS256 ), pl );

        jwsObject.sign( signer );

        return jwsObject.serialize();
    }
    catch ( Exception e )
    {
        LOG.error( "Error creating RSA token", e.getMessage() );

        return "";
    }
}
 
Example #14
Source File: EncryptionUtilityTest.java    From amex-api-java-client-core with Apache License 2.0 6 votes vote down vote up
@Test
public void checkObjectFailure() throws Exception {
    Method method = encryptionUtility.getClass().getDeclaredMethod("checkObject", JWSObject.class);

    method.setAccessible(true);
    JWSObject object = mock(JWSObject.class);

    Throwable exception = null;
    try {
        method.invoke(encryptionUtility, object);
    } catch(InvocationTargetException e) {
        exception = e.getCause();
    }

    assertNotNull(exception);
    assertTrue(exception instanceof CryptoException);
}
 
Example #15
Source File: EncryptionUtility.java    From amex-api-java-client-core with Apache License 2.0 6 votes vote down vote up
public String sign(String algorithm, String kid, String keyStr, String dataToSign) {
    try {

        Key key = getKey(algorithm, keyStr);

        JWSHeader.Builder jwsBuilder = new JWSHeader.Builder("HS256".equals(algorithm) ? JWSAlgorithm.HS256 : JWSAlgorithm.RS256);
        jwsBuilder.keyID(kid);

        JWSHeader signingHeader = jwsBuilder.build();
        JWSSigner signer = "HS256".equals(algorithm) ? new MACSigner(key.getEncoded()) : new RSASSASigner((RSAPrivateKey) key);
        JWSObject jwsObject = new JWSObject(signingHeader, new Payload(dataToSign));
        jwsObject.sign(signer);
        checkObject(jwsObject);

        String parts[] = jwsObject.serialize().split("\\.");

        return "{\"protected\":\"" + parts[0] + "\", \"payload\":\"" + parts[1] + "\", \"signature\":\"" + parts[2] + "\"}";

    } catch (Exception e) {
        throw new CryptoException("Exception signing data: " + e.getMessage(), e);
    }
}
 
Example #16
Source File: JWT.java    From api-server-seed with Apache License 2.0 6 votes vote down vote up
public static JWTUser getJWTUser(String token) throws JWTException {
	if (StringUtils.isEmpty(token)) {
		throw new JWTException("没有找到token信息!");
	}
	try {
		JWSObject jwsObject = JWSObject.parse(token);
		if (JWT.verify(jwsObject)) {
			// 判断有效期,不在有效期内则直接抛出错误
			JWTUser user = new JWTUser(jwsObject.getPayload().toJSONObject());
			if (user.getExp() >= Calendar.getInstance().getTimeInMillis()) {
				return user;
			} else {
				throw new JWTException("token已经超过有效期!");
			}
		} else {
			throw new JWTException("token校验失败!");
		}
	} catch (Exception e) {
		throw new JWTException(e);
	}
}
 
Example #17
Source File: LoginEncryptionUtils.java    From Geyser with MIT License 6 votes vote down vote up
private static boolean validateChainData(JsonNode data) throws Exception {
    ECPublicKey lastKey = null;
    boolean validChain = false;
    for (JsonNode node : data) {
        JWSObject jwt = JWSObject.parse(node.asText());

        if (!validChain) {
            validChain = EncryptionUtils.verifyJwt(jwt, EncryptionUtils.getMojangPublicKey());
        }

        if (lastKey != null) {
            EncryptionUtils.verifyJwt(jwt, lastKey);
        }

        JsonNode payloadNode = JSON_MAPPER.readTree(jwt.getPayload().toString());
        JsonNode ipkNode = payloadNode.get("identityPublicKey");
        Preconditions.checkState(ipkNode != null && ipkNode.getNodeType() == JsonNodeType.STRING, "identityPublicKey node is missing in chain");
        lastKey = EncryptionUtils.generateKey(ipkNode.asText());
    }
    return validChain;
}
 
Example #18
Source File: UpstreamPacketHandler.java    From ProxyPass with GNU Affero General Public License v3.0 6 votes vote down vote up
private static boolean validateChainData(JsonNode data) throws Exception {
    ECPublicKey lastKey = null;
    boolean validChain = false;
    for (JsonNode node : data) {
        JWSObject jwt = JWSObject.parse(node.asText());

        if (!validChain) {
            validChain = verifyJwt(jwt, EncryptionUtils.getMojangPublicKey());
        }

        if (lastKey != null) {
            verifyJwt(jwt, lastKey);
        }

        JsonNode payloadNode = ProxyPass.JSON_MAPPER.readTree(jwt.getPayload().toString());
        JsonNode ipkNode = payloadNode.get("identityPublicKey");
        Preconditions.checkState(ipkNode != null && ipkNode.getNodeType() == JsonNodeType.STRING, "identityPublicKey node is missing in chain");
        lastKey = EncryptionUtils.generateKey(ipkNode.asText());
    }
    return validChain;
}
 
Example #19
Source File: JwkKeyPairManager.java    From OAuth-2.0-Cookbook with MIT License 6 votes vote down vote up
public String getSignedContent(String content) {
    Payload contentPayload = new Payload(content);

    try {
        RSASSASigner rsa = new RSASSASigner((RSAPrivateKey) clientJwk);
        JWSAlgorithm alg = JWSAlgorithm.RS256;
        JWSHeader header = new JWSHeader.Builder(alg)
            .keyID(clientJwk.getKeyID())
            .build();
        JWSObject jws = new JWSObject(header, contentPayload);
        jws.sign(rsa);
        return jws.serialize();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example #20
Source File: JwtLoginService.java    From cruise-control with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private boolean validateSignature(SignedJWT jwtToken) {
  if (JWSObject.State.SIGNED != jwtToken.getState() || jwtToken.getSignature() == null) {
    return false;
  }
  JWSVerifier verifier = new RSASSAVerifier(_publicKey);
  try {
    return jwtToken.verify(verifier);
  } catch (JOSEException e) {
    JWT_LOGGER.warn("Couldn't verify the signature of a token", e);
    return false;
  }
}
 
Example #21
Source File: JWTUtils.java    From java-11-examples with Apache License 2.0 5 votes vote down vote up
public static JWToken issue(String subject, String keyId, PrivateKey privateKey, Long expires) throws JOSEException {

        JSONObject payload = new JSONObject();
        JWSHeader header = new JWSHeader(JWSAlgorithm.RS256, JOSEObjectType.JWT, null, null, null, null, null, null, null, null, keyId, null, null);
        payload.put("sub", subject);
        payload.put("exp", expires);
        JWSObject jwsObject = new JWSObject(header, new Payload(payload));
        jwsObject.sign(new RSASSASigner(privateKey));
        return new JWToken(jwsObject.serialize());
    }
 
Example #22
Source File: LoginEncryptionUtils.java    From Geyser with MIT License 5 votes vote down vote up
private static void encryptConnectionWithCert(GeyserConnector connector, GeyserSession session, String clientData, JsonNode certChainData) {
    try {
        boolean validChain = validateChainData(certChainData);

        connector.getLogger().debug(String.format("Is player data valid? %s", validChain));

        JWSObject jwt = JWSObject.parse(certChainData.get(certChainData.size() - 1).asText());
        JsonNode payload = JSON_MAPPER.readTree(jwt.getPayload().toBytes());

        if (payload.get("extraData").getNodeType() != JsonNodeType.OBJECT) {
            throw new RuntimeException("AuthData was not found!");
        }

        JsonNode extraData = payload.get("extraData");
        session.setAuthenticationData(new AuthData(
                extraData.get("displayName").asText(),
                UUID.fromString(extraData.get("identity").asText()),
                extraData.get("XUID").asText()
        ));

        if (payload.get("identityPublicKey").getNodeType() != JsonNodeType.STRING) {
            throw new RuntimeException("Identity Public Key was not found!");
        }

        ECPublicKey identityPublicKey = EncryptionUtils.generateKey(payload.get("identityPublicKey").textValue());
        JWSObject clientJwt = JWSObject.parse(clientData);
        EncryptionUtils.verifyJwt(clientJwt, identityPublicKey);

        session.setClientData(JSON_MAPPER.convertValue(JSON_MAPPER.readTree(clientJwt.getPayload().toBytes()), BedrockClientData.class));

        if (EncryptionUtils.canUseEncryption()) {
            LoginEncryptionUtils.startEncryptionHandshake(session, identityPublicKey);
        }
    } catch (Exception ex) {
        session.disconnect("disconnectionScreen.internalError.cantConnect");
        throw new RuntimeException("Unable to complete login", ex);
    }
}
 
Example #23
Source File: ClientChainData.java    From Nukkit with GNU General Public License v3.0 5 votes vote down vote up
private boolean verifyChain(List<String> chains) throws Exception {

        PublicKey lastKey = null;
        boolean mojangKeyVerified = false;
        for (String chain: chains) {
            JWSObject jws = JWSObject.parse(chain);

            if (!mojangKeyVerified) {
                // First chain should be signed using Mojang's private key. We'd be in big trouble if it leaked...
                mojangKeyVerified = verify(MOJANG_PUBLIC_KEY, jws);
            }

            if (lastKey != null) {
                if (!verify(lastKey, jws)) {
                    throw new JOSEException("Unable to verify key in chain.");
                }
            }

            JSONObject payload = jws.getPayload().toJSONObject();
            String base64key = payload.getAsString("identityPublicKey");
            if (base64key == null) {
                throw new RuntimeException("No key found");
            }
            lastKey = generateKey(base64key);
        }
        return mojangKeyVerified;
    }
 
Example #24
Source File: AtlasKnoxSSOAuthenticationFilter.java    From incubator-atlas with Apache License 2.0 5 votes vote down vote up
/**
 * Verify the signature of the JWT token in this method. This method depends
 * on the public key that was established during init based upon the
 * provisioned public key. Override this method in subclasses in order to
 * customize the signature verification behavior.
 *
 * @param jwtToken the token that contains the signature to be validated
 * @return valid true if signature verifies successfully; false otherwise
 */
protected boolean validateSignature(SignedJWT jwtToken) {
    boolean valid = false;
    if (JWSObject.State.SIGNED == jwtToken.getState()) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("SSO token is in a SIGNED state");
        }
        if (jwtToken.getSignature() != null) {
            if (LOG.isDebugEnabled()) {
                LOG.debug("SSO token signature is not null");
            }
            try {
                if (verifier != null && jwtToken.verify(verifier)) {
                    valid = true;
                    if (LOG.isDebugEnabled()) {
                        LOG.debug("SSO token has been successfully verified");
                    }
                } else {
                    LOG.warn("SSO signature verification failed.Please check the public key");
                }
            } catch (JOSEException je) {
                LOG.warn("Error while validating signature", je);
            } catch (Exception e) {
                LOG.warn("Error while validating signature", e);
            }
        }
    }
    return valid;
}
 
Example #25
Source File: ZendeskRedirectServlet.java    From codenvy with Eclipse Public License 1.0 5 votes vote down vote up
@Override
protected void service(HttpServletRequest request, HttpServletResponse response)
    throws IOException, ServletException {

  if (shared_key == null || subdomain == null)
    throw new ServletException("Zendesk is not configured.");
  // Given a user instance
  // Compose the JWT claims set
  JWTClaimsSet jwtClaims = new JWTClaimsSet();
  jwtClaims.setIssueTime(new Date());
  jwtClaims.setJWTID(UUID.randomUUID().toString());
  Subject subject = EnvironmentContext.getCurrent().getSubject();
  jwtClaims.setCustomClaim("name", getName());
  jwtClaims.setCustomClaim("email", subject.getUserName());
  // Create JWS header with HS256 algorithm
  JWSHeader header = new JWSHeader(JWSAlgorithm.HS256);
  JWSObject jwsObject = new JWSObject(header, new Payload(jwtClaims.toJSONObject()));
  // Create HMAC signer
  JWSSigner signer = new MACSigner(shared_key.getBytes());
  try {
    jwsObject.sign(signer);
  } catch (JOSEException e) {
    String msg = String.format("Error signing JWT: %s", e.getMessage());
    LOG.warn(msg);
    response.sendError(500, msg);
  }
  // Serialise to JWT compact form
  String jwtString = jwsObject.serialize();
  String redirectUrl = "https://" + subdomain + ".zendesk.com/access/jwt?jwt=" + jwtString;
  response.sendRedirect(redirectUrl);
}
 
Example #26
Source File: Jwt.java    From JWT with MIT License 5 votes vote down vote up
/**
    * 校验token是否合法,返回Map集合,集合中主要包含    state状态码   data鉴权成功后从token中提取的数据
    * 该方法在过滤器中调用,每次请求API时都校验
    * @param token
    * @return  Map<String, Object>
    */
public static Map<String, Object> validToken(String token) {
	Map<String, Object> resultMap = new HashMap<String, Object>();
	try {
		JWSObject jwsObject = JWSObject.parse(token);
		Payload payload = jwsObject.getPayload();
		JWSVerifier verifier = new MACVerifier(SECRET);

		if (jwsObject.verify(verifier)) {
			JSONObject jsonOBj = payload.toJSONObject();
			// token校验成功(此时没有校验是否过期)
			resultMap.put("state", TokenState.VALID.toString());
			// 若payload包含ext字段,则校验是否过期
			if (jsonOBj.containsKey("ext")) {
				long extTime = Long.valueOf(jsonOBj.get("ext").toString());
				long curTime = new Date().getTime();
				// 过期了
				if (curTime > extTime) {
					resultMap.clear();
					resultMap.put("state", TokenState.EXPIRED.toString());
				}
			}
			resultMap.put("data", jsonOBj);

		} else {
			// 校验失败
			resultMap.put("state", TokenState.INVALID.toString());
		}

	} catch (Exception e) {
		//e.printStackTrace();
		// token格式不合法导致的异常
		resultMap.clear();
		resultMap.put("state", TokenState.INVALID.toString());
	}
	return resultMap;
}
 
Example #27
Source File: Jwt.java    From JWT with MIT License 5 votes vote down vote up
/**
 * 生成token,该方法只在用户登录成功后调用
 * 
 * @param Map集合,可以存储用户id,token生成时间,token过期时间等自定义字段
 * @return token字符串,若失败则返回null
 */
public static String createToken(Map<String, Object> payload) {
	String tokenString=null;
	// 创建一个 JWS object
	JWSObject jwsObject = new JWSObject(header, new Payload(new JSONObject(payload)));
	try {
		// 将jwsObject 进行HMAC签名
		jwsObject.sign(new MACSigner(SECRET));
		tokenString=jwsObject.serialize();
	} catch (JOSEException e) {
		System.err.println("签名失败:" + e.getMessage());
		e.printStackTrace();
	}
	return tokenString;
}
 
Example #28
Source File: EncryptionUtils.java    From Protocol with Apache License 2.0 5 votes vote down vote up
/**
 * Verify the validity of the login chain data from the {@link com.nukkitx.protocol.bedrock.packet.LoginPacket}
 *
 * @param chain array of JWS objects
 * @return chain validity
 * @throws JOSEException            invalid JWS algorithm used
 * @throws ParseException           invalid JWS object
 * @throws InvalidKeySpecException  invalid EC key provided
 * @throws NoSuchAlgorithmException runtime does not support EC spec
 */
public static boolean verifyChain(JSONArray chain) throws JOSEException, ParseException, InvalidKeySpecException, NoSuchAlgorithmException {
    ECPublicKey lastKey = null;
    boolean validChain = false;
    for (Object node : chain) {
        Preconditions.checkArgument(node instanceof String, "Chain node is not a string");
        JWSObject jwt = JWSObject.parse((String) node);

        if (lastKey == null) {
            validChain = verifyJwt(jwt, MOJANG_PUBLIC_KEY);
        } else {
            validChain = verifyJwt(jwt, lastKey);
        }

        if (!validChain) {
            break;
        }

        Object payload = JSONValue.parse(jwt.getPayload().toString());
        Preconditions.checkArgument(payload instanceof JSONObject, "Payload is not a object");

        Object identityPublicKey = ((JSONObject) payload).get("identityPublicKey");
        Preconditions.checkArgument(identityPublicKey instanceof String, "identityPublicKey node is missing in chain");
        lastKey = generateKey((String) identityPublicKey);
    }
    return validChain;
}
 
Example #29
Source File: EncryptionUtils.java    From Protocol with Apache License 2.0 5 votes vote down vote up
/**
 * Create handshake JWS used in the {@link com.nukkitx.protocol.bedrock.packet.ServerToClientHandshakePacket}
 * which completes the encryption handshake.
 *
 * @param serverKeyPair used to sign the JWT
 * @param token         salt for the encryption handshake
 * @return signed JWS object
 * @throws JOSEException invalid key pair provided
 */
public static JWSObject createHandshakeJwt(KeyPair serverKeyPair, byte[] token) throws JOSEException {
    URI x5u = URI.create(Base64.getEncoder().encodeToString(serverKeyPair.getPublic().getEncoded()));

    JWTClaimsSet claimsSet = new JWTClaimsSet.Builder().claim("salt", Base64.getEncoder().encodeToString(token)).build();
    SignedJWT jwt = new SignedJWT(new JWSHeader.Builder(JWSAlgorithm.ES384).x509CertURL(x5u).build(), claimsSet);

    signJwt(jwt, (ECPrivateKey) serverKeyPair.getPrivate());

    return jwt;
}
 
Example #30
Source File: TokenUtil.java    From peer-os with Apache License 2.0 5 votes vote down vote up
public static long getDate( JWSObject jwsObject )
{
    try
    {
        Payload payload = parseToken( jwsObject );
        JSONObject obj = payload.toJSONObject();
        return ( long ) obj.get( "exp" );
    }
    catch ( Exception e )
    {
        LOG.warn( e.getMessage() );
        return 0;
    }
}