com.nimbusds.jose.util.Base64URL Java Examples

The following examples show how to use com.nimbusds.jose.util.Base64URL. 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: 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 #2
Source File: JWKConverter.java    From graviteeio-access-management with Apache License 2.0 6 votes vote down vote up
public static OctetSequenceKey convert(io.gravitee.am.model.jose.OCTKey octKey) {
    try {
        //Base64URL k, KeyUse use, Set<KeyOperation> ops, Algorithm alg, String kid, URI x5u, Base64URL x5t, Base64URL x5t256, List<Base64> x5c, KeyStore ks
        return new OctetSequenceKey(
                new Base64URL(octKey.getK()),
                octKey.getUse() != null ? com.nimbusds.jose.jwk.KeyUse.parse(octKey.getUse()) : null,
                octKey.getKeyOps()!=null?KeyOperation.parse(octKey.getKeyOps().stream().collect(Collectors.toList())):null,
                octKey.getAlg()!=null?new Algorithm(octKey.getAlg()):null,
                octKey.getKid(),
                octKey.getX5u() != null ? URI.create(octKey.getX5u()) : null,
                octKey.getX5t() != null ? new Base64URL(octKey.getX5t()) : null,
                octKey.getX5tS256() != null ? new Base64URL(octKey.getX5tS256()) : null,
                octKey.getX5c() != null ? octKey.getX5c().stream().map(Base64::encode).collect(Collectors.toList()) : null,
                null
        );
    } catch (ParseException e) {
        throw new ServerErrorException("Malformed Octet Key Pair encryption");
    }
}
 
Example #3
Source File: JWKFilter.java    From graviteeio-access-management with Apache License 2.0 6 votes vote down vote up
/**
 * @return Filter to retrieve AES keys, with same size as the algorithm, expected use for encryption.
 */
public static Predicate<io.gravitee.am.model.jose.JWK> OCT_KEY_ENCRYPTION(JWEAlgorithm algorithm) {

    return jwk -> {
        int expectedKeySize;//AES require same size key/alg
        if (JWEAlgorithm.A128KW.equals(algorithm) || JWEAlgorithm.A128GCMKW.equals(algorithm)) {
            expectedKeySize = 16;//128/8
        } else if (JWEAlgorithm.A192KW.equals(algorithm) || JWEAlgorithm.A192GCMKW.equals(algorithm)) {
            expectedKeySize = 24;//192/8
        } else if (JWEAlgorithm.A256KW.equals(algorithm) || JWEAlgorithm.A256GCMKW.equals(algorithm)) {
            expectedKeySize = 32;//256/8
        } else {
            return false;
        }

        return jwk != null && KeyType.OCT.getKeyType().equals(jwk.getKty()) &&
                ((io.gravitee.am.model.jose.OCTKey)jwk).getK()!=null &&
                new Base64URL(((io.gravitee.am.model.jose.OCTKey)jwk).getK()).decode().length == expectedKeySize &&
                (KeyUse.ENCRYPTION.getValue().equals(jwk.getUse()) || jwk.getUse() == null);
    };
}
 
Example #4
Source File: JWSServiceImpl.java    From graviteeio-access-management with Apache License 2.0 5 votes vote down vote up
private JWSVerifier from(OKPKey okpKey) {
    try {
        Curve curve = Curve.parse(okpKey.getCrv());
        if(curve.getStdName()==null) {
            throw new IllegalArgumentException("Unknown OKP Curve: "+okpKey.getCrv());
        }
        OctetKeyPair jwk = new OctetKeyPair.Builder(curve,new Base64URL(okpKey.getX())).build();
        return new Ed25519Verifier(jwk);
    }
    catch (JOSEException ex) {
        LOGGER.error("Unable to build Verifier from Message Authentication Code (MAC) key",ex);
        throw new IllegalArgumentException("Signature is using and unknown/not managed key");
    }
}
 
Example #5
Source File: JWTToken.java    From knox with Apache License 2.0 5 votes vote down vote up
@Override
public byte[] getSignaturePayload() {
  byte[] b = null;
  Base64URL b64 = jwt.getSignature();
  if (b64 != null) {
    b = b64.decode();
  }
  return b;
}
 
Example #6
Source File: ShibbolethAcrAwareTokenService.java    From shibboleth-oidc with Apache License 2.0 5 votes vote down vote up
/**
 * Calculate at hash claim.
 *
 * @param accessToken   the access token
 * @param signingAlg    the signing alg
 * @param idClaims      the id claims
 * @param responseTypes the response types
 */
private void calculateAtHashClaim(final OAuth2AccessTokenEntity accessToken,
                                  final JWSAlgorithm signingAlg, final JWTClaimsSet.Builder idClaims,
                                  final Set<String> responseTypes) {
    if (responseTypes.contains(OIDCConstants.TOKEN)) {
        // calculate the token hash
        final Base64URL atHash = IdTokenHashUtils.getAccessTokenHash(signingAlg, accessToken);
        idClaims.claim(OIDCConstants.AT_HASH, atHash);

        log.debug("{} is set to {}", OIDCConstants.AT_HASH, atHash);
    }
}
 
Example #7
Source File: MACVerifierExtended.java    From shiro-jwt with MIT License 5 votes vote down vote up
@Override
public boolean verify(final JWSHeader header, final byte[] signingInput, final Base64URL signature) throws JOSEException {
    boolean value = super.verify(header, signingInput, signature);
    long time = System.currentTimeMillis();

    return value && claimsSet.getNotBeforeTime().getTime() <= time && time < claimsSet.getExpirationTime().getTime();
}
 
Example #8
Source File: ClientSelfSignedAuthProvider.java    From graviteeio-access-management with Apache License 2.0 5 votes vote down vote up
private static String getThumbprint(X509Certificate cert, String algorithm)
        throws NoSuchAlgorithmException, CertificateEncodingException {
    MessageDigest md = MessageDigest.getInstance(algorithm);
    byte[] der = cert.getEncoded();
    md.update(der);
    byte[] digest = md.digest();
    return Base64URL.encode(digest).toString();
}
 
Example #9
Source File: STSJWTBuilder.java    From cellery-security with Apache License 2.0 5 votes vote down vote up
private JWSHeader buildJWSHeader() throws KeyResolverException, CertificateEncodingException,
        NoSuchAlgorithmException {

    String certThumbPrint = null;
    certThumbPrint = CertificateUtils.getThumbPrint(CertificateUtils.getKeyResolver().getCertificate());
    headerBuilder.keyID(certThumbPrint);
    headerBuilder.x509CertThumbprint(new Base64URL(certThumbPrint));
    return headerBuilder.build();
}
 
Example #10
Source File: JWSServiceImpl.java    From graviteeio-access-management with Apache License 2.0 5 votes vote down vote up
private JWSVerifier from(OCTKey octKey) {
    try {
        OctetSequenceKey jwk = new OctetSequenceKey.Builder(new Base64URL(octKey.getK())).build();
        return new MACVerifier(jwk);
    }
    catch (JOSEException ex) {
        LOGGER.error("Unable to build Verifier from Edwards Curve (OKP) key",ex);
        throw new IllegalArgumentException("Signature is using and unknown/not managed key");
    }
}
 
Example #11
Source File: JWKFilter.java    From graviteeio-access-management with Apache License 2.0 5 votes vote down vote up
/**
 * @return Filter to retrieve AES keys, with same size as the algorithm, expected use for encryption.
 */
public static Predicate<io.gravitee.am.model.jose.JWK> OCT_KEY_ENCRYPTION(EncryptionMethod encryptionMethod) {
    return jwk -> jwk != null && KeyType.OCT.getKeyType().equals(jwk.getKty()) &&
            ((io.gravitee.am.model.jose.OCTKey)jwk).getK()!=null &&
            new Base64URL(((io.gravitee.am.model.jose.OCTKey)jwk).getK()).decode().length*8 == encryptionMethod.cekBitLength() &&
            (KeyUse.ENCRYPTION.getValue().equals(jwk.getUse()) || jwk.getUse() == null);
}
 
Example #12
Source File: JWKConverter.java    From graviteeio-access-management with Apache License 2.0 5 votes vote down vote up
public static OctetKeyPair convert(io.gravitee.am.model.jose.OKPKey okpKey) {
    try {
        if (!okpKey.isPrivate()) {
            //Curve crv, Base64URL x, KeyUse use, Set<KeyOperation> ops, Algorithm alg, String kid, URI x5u, Base64URL x5t, Base64URL x5t256, List<Base64> x5c, KeyStore ks
            return new OctetKeyPair(
                    Curve.parse(okpKey.getCrv()),
                    new Base64URL(okpKey.getX()),
                    okpKey.getUse() != null ? com.nimbusds.jose.jwk.KeyUse.parse(okpKey.getUse()) : null,
                    okpKey.getKeyOps() != null ? KeyOperation.parse(okpKey.getKeyOps().stream().collect(Collectors.toList())) : null,
                    okpKey.getAlg() != null ? new Algorithm(okpKey.getAlg()) : null,
                    okpKey.getKid(),
                    okpKey.getX5u() != null ? URI.create(okpKey.getX5u()) : null,
                    okpKey.getX5t() != null ? new Base64URL(okpKey.getX5t()) : null,
                    okpKey.getX5tS256() != null ? new Base64URL(okpKey.getX5tS256()) : null,
                    okpKey.getX5c() != null ? okpKey.getX5c().stream().map(Base64::encode).collect(Collectors.toList()) : null,
                    null
            );
        } else {
            return new OctetKeyPair(
                    Curve.parse(okpKey.getCrv()),
                    new Base64URL(okpKey.getX()),
                    new Base64URL(okpKey.getD()),
                    okpKey.getUse() != null ? com.nimbusds.jose.jwk.KeyUse.parse(okpKey.getUse()) : null,
                    okpKey.getKeyOps() != null ? KeyOperation.parse(okpKey.getKeyOps().stream().collect(Collectors.toList())) : null,
                    okpKey.getAlg() != null ? new Algorithm(okpKey.getAlg()) : null,
                    okpKey.getKid(),
                    okpKey.getX5u() != null ? URI.create(okpKey.getX5u()) : null,
                    okpKey.getX5t() != null ? new Base64URL(okpKey.getX5t()) : null,
                    okpKey.getX5tS256() != null ? new Base64URL(okpKey.getX5tS256()) : null,
                    okpKey.getX5c() != null ? okpKey.getX5c().stream().map(Base64::encode).collect(Collectors.toList()) : null,
                    null);
        }
    } catch (ParseException e) {
        throw new ServerErrorException("Malformed Octet Key Pair encryption");
    }
}
 
Example #13
Source File: JWKConverter.java    From graviteeio-access-management with Apache License 2.0 5 votes vote down vote up
public static com.nimbusds.jose.jwk.ECKey convert(io.gravitee.am.model.jose.ECKey ecKey) {
    try {
        if (!ecKey.isPrivate()) {
            //Curve crv, Base64URL x, Base64URL y, KeyUse use, Set<KeyOperation> ops, Algorithm alg, String kid, URI x5u, Base64URL x5t, Base64URL x5t256, List<Base64> x5c, KeyStore ks
            return new com.nimbusds.jose.jwk.ECKey(
                    Curve.parse(ecKey.getCrv()),
                    new Base64URL(ecKey.getX()),
                    new Base64URL(ecKey.getY()),
                    ecKey.getUse() != null ? com.nimbusds.jose.jwk.KeyUse.parse(ecKey.getUse()) : null,
                    ecKey.getKeyOps() != null ? KeyOperation.parse(ecKey.getKeyOps().stream().collect(Collectors.toList())) : null,
                    ecKey.getAlg() != null ? new Algorithm(ecKey.getAlg()) : null,
                    ecKey.getKid(),
                    ecKey.getX5u() != null ? URI.create(ecKey.getX5u()) : null,
                    ecKey.getX5t() != null ? new Base64URL(ecKey.getX5t()) : null,
                    ecKey.getX5tS256() != null ? new Base64URL(ecKey.getX5tS256()) : null,
                    ecKey.getX5c() != null ? ecKey.getX5c().stream().map(Base64::encode).collect(Collectors.toList()) : null,
                    null
            );
        } else {
            return new com.nimbusds.jose.jwk.ECKey(
                    Curve.parse(ecKey.getCrv()),
                    new Base64URL(ecKey.getX()),
                    new Base64URL(ecKey.getY()),
                    new Base64URL(ecKey.getD()),
                    ecKey.getUse() != null ? com.nimbusds.jose.jwk.KeyUse.parse(ecKey.getUse()) : null,
                    ecKey.getKeyOps() != null ? KeyOperation.parse(ecKey.getKeyOps().stream().collect(Collectors.toList())) : null,
                    ecKey.getAlg() != null ? new Algorithm(ecKey.getAlg()) : null,
                    ecKey.getKid(),
                    ecKey.getX5u() != null ? URI.create(ecKey.getX5u()) : null,
                    ecKey.getX5t() != null ? new Base64URL(ecKey.getX5t()) : null,
                    ecKey.getX5tS256() != null ? new Base64URL(ecKey.getX5tS256()) : null,
                    ecKey.getX5c() != null ? ecKey.getX5c().stream().map(Base64::encode).collect(Collectors.toList()) : null,
                    null);
        }
    } catch (ParseException e) {
        throw new ServerErrorException("Malformed Elliptic Curve key encryption");
    }
}
 
Example #14
Source File: CellerySignedJWTBuilder.java    From cellery-security with Apache License 2.0 5 votes vote down vote up
private JWSHeader buildJWSHeader() throws IdentityOAuth2Exception {

        String certThumbPrint = OAuth2Util.getThumbPrint(TENANT_DOMAIN, TENANT_ID);
        headerBuilder.keyID(certThumbPrint);
        headerBuilder.x509CertThumbprint(new Base64URL(certThumbPrint));
        return headerBuilder.build();
    }
 
Example #15
Source File: IdTokenHashUtils.java    From MaxKey with Apache License 2.0 4 votes vote down vote up
public static Base64URL getHash(JWSAlgorithm signingAlg, byte[] bytes) {

		//Switch based on the given signing algorithm - use SHA-xxx with the same 'xxx' bitnumber
		//as the JWSAlgorithm to hash the token.
		String hashAlg = null;

		if (signingAlg.equals(JWSAlgorithm.HS256) || signingAlg.equals(JWSAlgorithm.ES256) || signingAlg.equals(JWSAlgorithm.RS256)) {
			hashAlg = "SHA-256";
		}

		else if (signingAlg.equals(JWSAlgorithm.ES384) || signingAlg.equals(JWSAlgorithm.HS384) || signingAlg.equals(JWSAlgorithm.RS384)) {
			hashAlg = "SHA-384";
		}

		else if (signingAlg.equals(JWSAlgorithm.ES512) || signingAlg.equals(JWSAlgorithm.HS512) || signingAlg.equals(JWSAlgorithm.RS512)) {
			hashAlg = "SHA-512";
		}

		if (hashAlg != null) {

			try {
				MessageDigest hasher = MessageDigest.getInstance(hashAlg);
				hasher.reset();
				hasher.update(bytes);

				byte[] hashBytes = hasher.digest();
				byte[] hashBytesLeftHalf = Arrays.copyOf(hashBytes, hashBytes.length / 2);
				Base64URL encodedHash = Base64URL.encode(hashBytesLeftHalf);

				return encodedHash;

			} catch (NoSuchAlgorithmException e) {

				logger.error("No such algorithm error: ", e);

			}

		}

		return null;
	}
 
Example #16
Source File: JWTToken.java    From knox with Apache License 2.0 4 votes vote down vote up
private JWTToken(String header, String claims, String signature) throws ParseException {
  jwt = new SignedJWT(new Base64URL(header), new Base64URL(claims), new Base64URL(signature));
}
 
Example #17
Source File: JWKConverter.java    From graviteeio-access-management with Apache License 2.0 4 votes vote down vote up
/*********************************
 * FROM GRAVITEE MODEL TO NIMBUS *
 *********************************/

public static com.nimbusds.jose.jwk.RSAKey convert(io.gravitee.am.model.jose.RSAKey rsaKey) {
    try {
        if (!rsaKey.isPrivate()) {
            //Base64URL n, Base64URL e, KeyUse use, Set<KeyOperation> ops, Algorithm alg, String kid, URI x5u, Base64URL x5t, Base64URL x5t256, List<Base64> x5c, KeyStore ks
            return new com.nimbusds.jose.jwk.RSAKey(
                    new Base64URL(rsaKey.getN()),
                    new Base64URL(rsaKey.getE()),
                    rsaKey.getUse() != null ? com.nimbusds.jose.jwk.KeyUse.parse(rsaKey.getUse()) : null,
                    rsaKey.getKeyOps()!=null? KeyOperation.parse(new ArrayList<>(rsaKey.getKeyOps())):null,
                    rsaKey.getAlg()!=null?new Algorithm(rsaKey.getAlg()):null,
                    rsaKey.getKid(),
                    rsaKey.getX5u() != null ? URI.create(rsaKey.getX5u()) : null,
                    rsaKey.getX5t() != null ? new Base64URL(rsaKey.getX5t()) : null,
                    rsaKey.getX5tS256() != null ? new Base64URL(rsaKey.getX5tS256()) : null,
                    rsaKey.getX5c() != null ? rsaKey.getX5c().stream().map(Base64::encode).collect(Collectors.toList()) : null,
                    null
            );
        } else {
            return new com.nimbusds.jose.jwk.RSAKey(
                    new Base64URL(rsaKey.getN()),
                    new Base64URL(rsaKey.getE()),
                    rsaKey.getD() != null ? new Base64URL(rsaKey.getD()) : null,
                    rsaKey.getP() != null ? new Base64URL(rsaKey.getP()) : null,
                    rsaKey.getQ() != null ? new Base64URL(rsaKey.getQ()) : null,
                    rsaKey.getDp() != null ? new Base64URL(rsaKey.getDp()) : null,
                    rsaKey.getDq() != null ? new Base64URL(rsaKey.getDq()) : null,
                    rsaKey.getQi() != null ? new Base64URL(rsaKey.getQi()) : null,
                    null,
                    rsaKey.getUse() != null ? com.nimbusds.jose.jwk.KeyUse.parse(rsaKey.getUse()) : null,
                    rsaKey.getKeyOps()!=null? KeyOperation.parse(new ArrayList<>(rsaKey.getKeyOps())):null,
                    rsaKey.getAlg()!=null?new Algorithm(rsaKey.getAlg()):null,
                    rsaKey.getKid(),
                    rsaKey.getX5u() != null ? URI.create(rsaKey.getX5u()) : null,
                    rsaKey.getX5t() != null ? new Base64URL(rsaKey.getX5t()) : null,
                    rsaKey.getX5tS256() != null ? new Base64URL(rsaKey.getX5tS256()) : null,
                    rsaKey.getX5c() != null ? rsaKey.getX5c().stream().map(Base64::encode).collect(Collectors.toList()) : null);
        }
    } catch (ParseException e) {
        throw new ServerErrorException("Malformed rsa key encryption");
    }
}
 
Example #18
Source File: IdTokenHashUtils.java    From MaxKey with Apache License 2.0 3 votes vote down vote up
/**
 * Compute the SHA hash of a token
 * 
 * @param signingAlg
 * @param token
 * @return
 */
public static Base64URL getAccessTokenHash(JWSAlgorithm signingAlg, JWT jwt) {

	byte[] tokenBytes = jwt.serialize().getBytes();

	return getHash(signingAlg, tokenBytes);

}
 
Example #19
Source File: IdTokenHashUtils.java    From MaxKey with Apache License 2.0 2 votes vote down vote up
/**
 * Compute the SHA hash of an authorization code
 * 
 * @param signingAlg
 * @param code
 * @return
 */
public static Base64URL getCodeHash(JWSAlgorithm signingAlg, String code) {
	return getHash(signingAlg, code.getBytes());
}