com.nimbusds.jose.jwk.RSAKey Java Examples

The following examples show how to use com.nimbusds.jose.jwk.RSAKey. 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: AuthorizationRequestParseRequestObjectHandlerTest.java    From graviteeio-access-management with Apache License 2.0 6 votes vote down vote up
@Test
public void invalid_request_object() throws Exception {
    RSAKey rsaKey = getRSAKey();
    JWSSigner signer = new RSASSASigner(rsaKey);

    JWTClaimsSet claimsSet = new JWTClaimsSet.Builder()
            .subject("alice")
            .issuer("https://c2id.com")
            .expirationTime(new Date(new Date().getTime() + 60 * 1000))
            .build();

    SignedJWT signedJWT = new SignedJWT(
            new JWSHeader.Builder(JWSAlgorithm.RS256).keyID("rsa-signature").build(),
            claimsSet);

    signedJWT.sign(signer);

    String jwt = signedJWT.serialize();
    System.out.println(jwt);
}
 
Example #2
Source File: AuthorizationRequestParseRequestObjectHandlerTest.java    From graviteeio-access-management with Apache License 2.0 6 votes vote down vote up
@Test
public void override_redirect_uri() throws Exception {
    RSAKey rsaKey = getRSAKey();
    JWSSigner signer = new RSASSASigner(rsaKey);

    JWTClaimsSet claimsSet = new JWTClaimsSet.Builder()
            .subject("alice")
            .issuer("https://c2id.com")
            .claim("redirect_uri", "https://op-test:60001/authz_cb")
            .expirationTime(new Date(new Date().getTime() + 60 * 1000))
            .build();

    SignedJWT signedJWT = new SignedJWT(
            new JWSHeader.Builder(JWSAlgorithm.RS256).keyID("rsa-signature").build(),
            claimsSet);

    signedJWT.sign(signer);

    String jwt = signedJWT.serialize();
    System.out.println(jwt);
}
 
Example #3
Source File: AuthorizationRequestParseRequestObjectHandlerTest.java    From graviteeio-access-management with Apache License 2.0 6 votes vote down vote up
@Test
public void override_max_age() throws Exception {
    RSAKey rsaKey = getRSAKey();
    JWSSigner signer = new RSASSASigner(rsaKey);

    JWTClaimsSet claimsSet = new JWTClaimsSet.Builder()
            .subject("alice")
            .issuer("https://c2id.com")
            .claim("max_age", 360000)
            .expirationTime(new Date(new Date().getTime() + 60 * 1000))
            .build();

    SignedJWT signedJWT = new SignedJWT(
            new JWSHeader.Builder(JWSAlgorithm.RS256).keyID("rsa-signature").build(),
            claimsSet);

    signedJWT.sign(signer);

    String jwt = signedJWT.serialize();
    System.out.println(jwt);
}
 
Example #4
Source File: AuthorizationRequestParseRequestObjectHandlerTest.java    From graviteeio-access-management with Apache License 2.0 6 votes vote down vote up
@Test
public void invalid_do_not_override_state_and_nonce() throws Exception {
    RSAKey rsaKey = getRSAKey();
    JWSSigner signer = new RSASSASigner(rsaKey);

    JWTClaimsSet claimsSet = new JWTClaimsSet.Builder()
            .subject("alice")
            .issuer("https://c2id.com")
            .claim("state", "override-state")
            .claim("nonce", "override-nonce")
            .expirationTime(new Date(new Date().getTime() + 60 * 1000))
            .build();

    SignedJWT signedJWT = new SignedJWT(
            new JWSHeader.Builder(JWSAlgorithm.RS256).keyID("rsa-signature").build(),
            claimsSet);

    signedJWT.sign(signer);

    String jwt = signedJWT.serialize();
    System.out.println(jwt);
}
 
Example #5
Source File: JwtAuthorizerTest.java    From outbackcdx with Apache License 2.0 6 votes vote down vote up
@Test
public void test() throws Exception {
    RSAKey rsaJWK = new RSAKeyGenerator(2048).generate();
    RSAKey rsaPublicJWK = rsaJWK.toPublicJWK();
    JWSSigner signer = new RSASSASigner(rsaJWK);
    JWTClaimsSet claimsSet = new JWTClaimsSet.Builder()
            .expirationTime(Date.from(Instant.now().plus(1, ChronoUnit.DAYS)))
            .claim("permissions", Arrays.asList(RULES_EDIT.toString(), INDEX_EDIT.toString()))
            .build();

    SignedJWT signedJWT = new SignedJWT(
            new JWSHeader.Builder(JWSAlgorithm.RS256).keyID(rsaJWK.getKeyID()).build(),
            claimsSet);
    signedJWT.sign(signer);
    String token = signedJWT.serialize();

    JwtAuthorizer authorizer = new JwtAuthorizer(new ImmutableJWKSet<>(new JWKSet(rsaPublicJWK)), "permissions");
    Set<Permission> permissions = authorizer.verify("beARer " + token).permissions;
    assertEquals(EnumSet.of(RULES_EDIT, INDEX_EDIT), permissions);
}
 
Example #6
Source File: OIDCJWKSTest.java    From syncope with Apache License 2.0 6 votes vote down vote up
@Test
public void save() throws Exception {
    OIDCJWKS jwks = entityFactory.newEntity(OIDCJWKS.class);

    RSAKey jwk = new RSAKeyGenerator(2048)
        .keyUse(KeyUse.SIGNATURE)
        .keyID(UUID.randomUUID().toString())
        .generate();

    String json = new JWKSet(jwk).toString();
    jwks.setJson(json);
    jwks = jwksDAO.save(jwks);
    assertNotNull(jwks);
    assertNotNull(jwks.getKey());

}
 
Example #7
Source File: AuthorizationRequestParseRequestObjectHandlerTest.java    From graviteeio-access-management with Apache License 2.0 6 votes vote down vote up
@Test
public void invalid_client() throws Exception {
    RSAKey rsaKey = getRSAKey();
    JWSSigner signer = new RSASSASigner(rsaKey);

    JWTClaimsSet claimsSet = new JWTClaimsSet.Builder()
            .subject("alice")
            .issuer("https://c2id.com")
            .claim("client_id", "unknown_client")
            .expirationTime(new Date(new Date().getTime() + 60 * 1000))
            .build();

    System.out.println(new PlainJWT(claimsSet).serialize());
    SignedJWT signedJWT = new SignedJWT(
            new JWSHeader.Builder(JWSAlgorithm.RS256).keyID("rsa-signature").build(),
            claimsSet);

    signedJWT.sign(signer);

    String jwt = signedJWT.serialize();
    System.out.println(jwt);
}
 
Example #8
Source File: CrossEncryptionTest.java    From oxAuth with MIT License 6 votes vote down vote up
private boolean testDecryptNimbusJoseJwt(String jwe) {

        try {
            EncryptedJWT encryptedJwt = EncryptedJWT.parse(jwe);
            //EncryptedJWT encryptedJwt = EncryptedJWT.parse(encryptWithGluu());
            //EncryptedJWT encryptedJwt = EncryptedJWT.parse(encryptWithNimbus());

            JWK jwk = JWK.parse(recipientJwkJson);
            RSAPrivateKey rsaPrivateKey = ((RSAKey) jwk).toRSAPrivateKey();

            JWEDecrypter decrypter = new RSADecrypter(rsaPrivateKey);
            decrypter.getJCAContext().setProvider(BouncyCastleProviderSingleton.getInstance());

            encryptedJwt.decrypt(decrypter);
            final String decryptedPayload = new String(Base64Util.base64urldecode(encryptedJwt.getPayload().toString()));
            System.out.println("Nimbusds decrypt succeed: " + decryptedPayload);
            if (isJsonEqual(decryptedPayload, PAYLOAD)) {
                return true;
            }
        } catch (Exception e) {
            System.out.println("Nimbusds decrypt failed: " + e.getMessage());
            e.printStackTrace();
        }
        return false;
    }
 
Example #9
Source File: CrossEncryptionTest.java    From oxAuth with MIT License 6 votes vote down vote up
public boolean testDecryptWithGluuDecrypter(String jwe) {

        try {
            JWK jwk = JWK.parse(recipientJwkJson);
            RSAPrivateKey rsaPrivateKey = ((RSAKey) jwk).toRSAPrivateKey();

            JweDecrypterImpl decrypter = new JweDecrypterImpl(rsaPrivateKey);

            decrypter.setKeyEncryptionAlgorithm(KeyEncryptionAlgorithm.RSA_OAEP);
            decrypter.setBlockEncryptionAlgorithm(BlockEncryptionAlgorithm.A128GCM);
            final String decryptedPayload = decrypter.decrypt(jwe).getClaims().toJsonString().toString();
            System.out.println("Gluu decrypt succeed: " + decryptedPayload);
            if (isJsonEqual(decryptedPayload, PAYLOAD)) {
                return true;
            }
        } catch (Exception e) {
            System.out.println("Gluu decrypt failed: " + e.getMessage());
            e.printStackTrace();
        }
        return false;
    }
 
Example #10
Source File: JWKSResponseBuilder.java    From cellery-security with Apache License 2.0 6 votes vote down vote up
/**
 * Builds the JSON response of JWKS.
 *
 * @param publicKey   Public Key which should be included in the jwks response.
 * @param certificate Certificate which should be in the jwks response.
 * @return JSON JWKS response.
 * @throws CertificateException
 * @throws NoSuchAlgorithmException
 * @throws ParseException
 */
public static String buildResponse(PublicKey publicKey, Certificate certificate) throws CertificateException,
        NoSuchAlgorithmException, ParseException {

    JSONArray jwksArray = new JSONArray();
    JSONObject jwksJson = new JSONObject();

    if (publicKey instanceof RSAPublicKey) {
        RSAKey.Builder jwk = new RSAKey.Builder((RSAPublicKey) publicKey);
        jwk.keyID(CertificateUtils.getThumbPrint(certificate));
        jwk.algorithm(JWSAlgorithm.RS256);
        jwk.keyUse(KeyUse.parse("sig"));
        jwksArray.put(jwk.build().toJSONObject());
        jwksJson.put("keys", jwksArray);
        log.debug(jwksJson.toString());
    }
    return jwksJson.toString();
}
 
Example #11
Source File: JweEncrypterImpl.java    From oxAuth with MIT License 6 votes vote down vote up
public JWEEncrypter createJweEncrypter() throws JOSEException, InvalidJweException, NoSuchAlgorithmException {
    final KeyEncryptionAlgorithm keyEncryptionAlgorithm = getKeyEncryptionAlgorithm();
    if (keyEncryptionAlgorithm == KeyEncryptionAlgorithm.RSA1_5 || keyEncryptionAlgorithm == KeyEncryptionAlgorithm.RSA_OAEP) {
        return new RSAEncrypter(new RSAKey.Builder((RSAPublicKey) publicKey).build());
    } else if (keyEncryptionAlgorithm == KeyEncryptionAlgorithm.A128KW || keyEncryptionAlgorithm == KeyEncryptionAlgorithm.A256KW) {
        if (sharedSymmetricKey == null) {
            throw new InvalidJweException("The shared symmetric key is null");
        }

        int keyLength = 16;
        if (keyEncryptionAlgorithm == KeyEncryptionAlgorithm.A256KW) {
            keyLength = 32;
        }

        if (sharedSymmetricKey.length != keyLength) {
            MessageDigest sha = MessageDigest.getInstance("SHA-256");
            sharedSymmetricKey = sha.digest(sharedSymmetricKey);
            sharedSymmetricKey = Arrays.copyOf(sharedSymmetricKey, keyLength);
        }

        return new AESEncrypter(sharedSymmetricKey);
    } else {
        throw new InvalidJweException("The key encryption algorithm is not supported");
    }
}
 
Example #12
Source File: KeyGeneratorUtil.java    From tomee with Apache License 2.0 6 votes vote down vote up
public static void generateKeyPair(String keyAlgorithm, int keySize) throws NoSuchAlgorithmException {
    KeyPairGenerator kpg = KeyPairGenerator.getInstance(keyAlgorithm); // RSA
    kpg.initialize(keySize); // 2048
    KeyPair kp = kpg.generateKeyPair();

    System.out.println("-----BEGIN PRIVATE KEY-----");
    System.out.println(Base64.getMimeEncoder().encodeToString(kp.getPrivate().getEncoded()));
    System.out.println("-----END PRIVATE KEY-----");
    System.out.println("-----BEGIN PUBLIC KEY-----");
    System.out.println(Base64.getMimeEncoder().encodeToString(kp.getPublic().getEncoded()));
    System.out.println("-----END PUBLIC KEY-----");

    RSAPublicKey publicKey = (RSAPublicKey) kp.getPublic();

    RSAKey jwk = new RSAKey.Builder(publicKey)
            .privateKey((RSAPrivateKey) kp.getPrivate())
            .keyUse(KeyUse.SIGNATURE)
            .keyID(UUID.randomUUID().toString())
            .build();

    System.out.println(jwk.toJSONObject().toJSONString());
}
 
Example #13
Source File: JwkSetEndpoint.java    From spring-cloud-demo with Apache License 2.0 5 votes vote down vote up
@GetMapping("/.well-known/jwks.json")
@ResponseBody
public Map<String, Object> getKey(Principal principal) {
    RSAPublicKey publicKey = (RSAPublicKey) this.keyPair.getPublic();
    RSAKey key = new RSAKey.Builder(publicKey).build();
    return new JWKSet(key).toJSONObject();
}
 
Example #14
Source File: AuthorizationRequestParseRequestObjectHandlerTest.java    From graviteeio-access-management with Apache License 2.0 5 votes vote down vote up
private RSAKey getRSAKey() throws Exception {
    File file = new File(getClass().getClassLoader().getResource("postman_request_object/request_object.key").toURI());
    FileInputStream fis = new FileInputStream(file);
    DataInputStream dis = new DataInputStream(fis);
    byte[] keyBytes = new byte[(int) file.length()];
    dis.readFully(keyBytes);
    dis.close();

    String content = IOUtils.readFileToString(file, StandardCharsets.UTF_8);
    return (RSAKey) JWK.parseFromPEMEncodedObjects(content);
}
 
Example #15
Source File: JwkKeyPairManager.java    From OAuth-2.0-Cookbook with MIT License 5 votes vote down vote up
public JwkKeyPairManager() {
    KeyPair keyPair = createRSA256KeyPair();
    RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
    RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
    RandomValueStringGenerator random = new RandomValueStringGenerator();
    RSAKey.Builder builder = new RSAKey.Builder(publicKey);
    builder.keyID(random.generate());
    builder.privateKey(privateKey);
    this.clientJwk = builder.build();
}
 
Example #16
Source File: JWTTokenGenerator.java    From micro-integrator with Apache License 2.0 5 votes vote down vote up
/**
 * Generate JWT Token with JWTTokenInfo object
 *
 * @param jwtToken JWT Token info object
 * @return Serialized JWT token
 * @throws JOSEException
 * @throws NoSuchAlgorithmException
 */
public String generateJWTToken(JWTTokenInfoDTO jwtToken) throws JOSEException, NoSuchAlgorithmException {

    KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(AuthConstants.TOKEN_STORE_KEY_ALGORITHM);
    keyPairGenerator.initialize(Integer.parseInt(JWTConfig.getInstance().getJwtConfigDto().getTokenSize()));
    RSAKey rsaJWK = generateRSAKey(jwtToken, keyPairGenerator); //Currently uses generated key pair

    SignedJWT signedJWT = populateSignedJWTToken(jwtToken, rsaJWK);

    JWSSigner signer = new RSASSASigner(rsaJWK);
    signedJWT.sign(signer);

    return signedJWT.serialize();
}
 
Example #17
Source File: TokenGenerator.java    From cruise-control with BSD 2-Clause "Simplified" License 5 votes vote down vote up
static TokenAndKeys generateToken(String subject, List<String> audience, long expirationTime) throws JOSEException {
  RSAKey rsaJwk = new RSAKeyGenerator(2048)
      .keyID("123")
      .generate();
  RSAKey rsaPublicJWK = rsaJwk.toPublicJWK();
  RSASSASigner signer = new RSASSASigner(rsaJwk);

  JWSHeader header = new JWSHeader.Builder(JWSAlgorithm.RS256)
      .type(JOSEObjectType.JWT)
      .build();
  JWTClaimsSet.Builder claimsSet = new JWTClaimsSet.Builder()
      .subject(subject)
      .issuer("https://linkedin.com");

  if (audience != null) {
    claimsSet.audience(audience);
  }

  if (expirationTime > 0) {
    claimsSet.expirationTime(new Date(expirationTime));
  } else {
    claimsSet.expirationTime(Date.from(Instant.now().plusSeconds(120)));
  }

  SignedJWT signedJWT = new SignedJWT(header, claimsSet.build());
  signedJWT.sign(signer);

  return new TokenAndKeys(signedJWT.serialize(), (RSAPrivateKey) signer.getPrivateKey(), rsaPublicJWK.toRSAPublicKey());
}
 
Example #18
Source File: AuthorizationRequestParseRequestObjectHandlerTest.java    From graviteeio-access-management with Apache License 2.0 5 votes vote down vote up
@Test
public void encrypted_request_object() throws Exception {
    RSAKey rsaKey = getRSAKey();
    JWSSigner signer = new RSASSASigner(rsaKey);

    JWTClaimsSet claimsSet = new JWTClaimsSet.Builder()
            .subject("alice")
            .issuer("https://c2id.com")
            .claim("redirect_uri", "https://op-test:60001/authz_cb")
            .expirationTime(new Date(new Date().getTime() + 60 * 1000))
            .build();

    SignedJWT signedJWT = new SignedJWT(
            new JWSHeader.Builder(JWSAlgorithm.RS256).keyID("rsa-encryption").build(),
            claimsSet);

    signedJWT.sign(signer);

    // Create JWE object with signed JWT as payload
    JWEObject jweObject = new JWEObject(
            new JWEHeader.Builder(JWEAlgorithm.RSA_OAEP_256, EncryptionMethod.A256GCM)
                    .contentType("JWT") // required to indicate nested JWT
                    .build(),
            new Payload(signedJWT));

    // Encrypt with the recipient's public key
    jweObject.encrypt(new RSAEncrypter(rsaKey));

    String jwt = jweObject.serialize();
    System.out.println(jwt);
}
 
Example #19
Source File: AuthorizationRequestParseRequestObjectHandlerTest.java    From graviteeio-access-management with Apache License 2.0 5 votes vote down vote up
@Test
public void encrypted_override_max_age() throws Exception {
    RSAKey rsaKey = getRSAKey();
    JWSSigner signer = new RSASSASigner(rsaKey);

    JWTClaimsSet claimsSet = new JWTClaimsSet.Builder()
            .subject("alice")
            .issuer("https://c2id.com")
            .claim("max_age", 360000)
            .expirationTime(new Date(new Date().getTime() + 60 * 1000))
            .build();

    SignedJWT signedJWT = new SignedJWT(
            new JWSHeader.Builder(JWSAlgorithm.RS256).keyID("rsa-signature").build(),
            claimsSet);

    signedJWT.sign(signer);

    // Create JWE object with signed JWT as payload
    JWEObject jweObject = new JWEObject(
            new JWEHeader.Builder(JWEAlgorithm.RSA_OAEP_256, EncryptionMethod.A256GCM)
                    .contentType("JWT") // required to indicate nested JWT
                    .build(),
            new Payload(signedJWT));

    // Encrypt with the recipient's public key
    jweObject.encrypt(new RSAEncrypter(rsaKey));

    String jwt = jweObject.serialize();
    System.out.println(jwt);
}
 
Example #20
Source File: AuthorizationRequestParseRequestObjectHandlerTest.java    From graviteeio-access-management with Apache License 2.0 5 votes vote down vote up
@Test
public void encrypted_override_redirect_uri() throws Exception {
    RSAKey rsaKey = getRSAKey();
    JWSSigner signer = new RSASSASigner(rsaKey);

    JWTClaimsSet claimsSet = new JWTClaimsSet.Builder()
            .subject("alice")
            .issuer("https://c2id.com")
            .claim("redirect_uri", "https://op-test:60001/authz_cb")
            .expirationTime(new Date(new Date().getTime() + 60 * 1000))
            .build();

    SignedJWT signedJWT = new SignedJWT(
            new JWSHeader.Builder(JWSAlgorithm.RS256).keyID("rsa-signature").build(),
            claimsSet);

    signedJWT.sign(signer);

    // Create JWE object with signed JWT as payload
    JWEObject jweObject = new JWEObject(
            new JWEHeader.Builder(JWEAlgorithm.RSA_OAEP_256, EncryptionMethod.A256GCM)
                    .contentType("JWT") // required to indicate nested JWT
                    .build(),
            new Payload(signedJWT));

    // Encrypt with the recipient's public key
    jweObject.encrypt(new RSAEncrypter(rsaKey));

    String jwt = jweObject.serialize();
    System.out.println(jwt);
}
 
Example #21
Source File: JwkAuthorizationServerConfiguration.java    From spring-security-oauth with MIT License 5 votes vote down vote up
@Bean
public JWKSet jwkSet() {
    RSAKey.Builder builder = new RSAKey.Builder((RSAPublicKey) keyPair().getPublic()).keyUse(KeyUse.SIGNATURE)
        .algorithm(JWSAlgorithm.RS256)
        .keyID(JWK_KID);
    return new JWKSet(builder.build());
}
 
Example #22
Source File: OIDCJWKSDataBinderImpl.java    From syncope with Apache License 2.0 5 votes vote down vote up
@Override
public OIDCJWKS create() {
    try {
        OIDCJWKS jwks = entityFactory.newEntity(OIDCJWKS.class);
        RSAKey jwk = new RSAKeyGenerator(2048)
            .keyUse(KeyUse.SIGNATURE)
            .keyID(SecureRandomUtils.generateRandomUUID().toString())
            .generate();
        jwks.setJson(new JWKSet(jwk).toString());
        return jwks;
    } catch (final Exception e) {
        throw new RuntimeException("Unable to create OIDC JWKS", e);
    }
}
 
Example #23
Source File: CrossEncryptionTest.java    From oxAuth with MIT License 5 votes vote down vote up
private String encryptWithGluuJweEncrypter() {

        try {
            RSAKey recipientPublicJWK = (RSAKey) (JWK.parse(recipientJwkJson));

            BlockEncryptionAlgorithm blockEncryptionAlgorithm = BlockEncryptionAlgorithm.A128GCM;
            KeyEncryptionAlgorithm keyEncryptionAlgorithm = KeyEncryptionAlgorithm.RSA_OAEP;
            Jwe jwe = new Jwe();
            jwe.getHeader().setType(JwtType.JWT);
            jwe.getHeader().setAlgorithm(keyEncryptionAlgorithm);
            jwe.getHeader().setEncryptionMethod(blockEncryptionAlgorithm);
            jwe.getClaims().setIssuer("https:devgluu.saminet.local");
            jwe.getClaims().setSubjectIdentifier("testing");
            jwe.getHeader().setKeyId("1");

            JweEncrypterImpl encrypter = new JweEncrypterImpl(keyEncryptionAlgorithm, blockEncryptionAlgorithm, recipientPublicJWK.toPublicKey());
            jwe = encrypter.encrypt(jwe);
            //		System.out.println("EncodedHeader: " + jwe.getEncodedHeader());
            //		System.out.println("EncodedEncryptedKey: " + jwe.getEncodedEncryptedKey());
            //		System.out.println("EncodedInitializationVector: " + jwe.getEncodedInitializationVector());
            //		System.out.println("EncodedCiphertext: " + jwe.getEncodedCiphertext());
            //		System.out.println("EncodedIntegrityValue: " + jwe.getEncodedIntegrityValue());
            return jwe.toString();
        } catch (Exception e) {
            System.out.println("Error encryption with Gluu JweEncrypter: " + e.getMessage());
            return null;
        }
    }
 
Example #24
Source File: CrossEncryptionTest.java    From oxAuth with MIT License 5 votes vote down vote up
@Test
public void nestedJWT() throws Exception {

    RSAKey senderJWK = (RSAKey) JWK.parse(senderJwkJson);

    RSAKey recipientPublicJWK = (RSAKey) (JWK.parse(recipientJwkJson));

    // Create JWT
    SignedJWT signedJWT = new SignedJWT(
            new JWSHeader.Builder(JWSAlgorithm.RS256).keyID(senderJWK.getKeyID()).build(),
            new JWTClaimsSet.Builder()
                    .subject("testi")
                    .issuer("https:devgluu.saminet.local")
                    .build());

    signedJWT.sign(new RSASSASigner(senderJWK));

    JWEObject jweObject = new JWEObject(
            new JWEHeader.Builder(JWEAlgorithm.RSA_OAEP, EncryptionMethod.A128GCM)
                    .contentType("JWT") // required to indicate nested JWT
                    .build(),
            new Payload(signedJWT));

    // Encrypt with the recipient's public key
    RSAEncrypter encrypter = new RSAEncrypter(recipientPublicJWK);
    jweObject.encrypt(encrypter);

    final String jweString = jweObject.serialize();

    decryptAndValidateSignatureWithGluu(jweString);
}
 
Example #25
Source File: JwkSetController.java    From platform with Apache License 2.0 5 votes vote down vote up
@Operation(summary = "JWKS")
@ApiResponse(description = "JWKS")
@GetMapping("/.well-known/jwks.json")
public Map<String, Object> getKey() {
    RSAPublicKey publicKey = (RSAPublicKey) this.keyPair.getPublic();
    RSAKey key = new RSAKey.Builder(publicKey).build();
    return new JWKSet(key).toJSONObject();
}
 
Example #26
Source File: JwtUtils.java    From platform with Apache License 2.0 5 votes vote down vote up
public static void generateRsaKey2() throws Exception {
    RSAKey jwk = new RSAKeyGenerator(2048)
            .keyUse(KeyUse.SIGNATURE)
            .keyID(UUID.randomUUID().toString())
            .generate();
    System.out.println(jwk);
    System.out.println(jwk.toPublicJWK());
}
 
Example #27
Source File: JwtUtils.java    From platform with Apache License 2.0 5 votes vote down vote up
public static void generateRsaKey3() throws Exception {
    KeyPairGenerator gen = KeyPairGenerator.getInstance("RSA");
    gen.initialize(2048);
    KeyPair keyPair = gen.generateKeyPair();

    JWK jwk = new RSAKey.Builder((RSAPublicKey) keyPair.getPublic())
            .privateKey((RSAPrivateKey) keyPair.getPrivate())
            .keyUse(KeyUse.SIGNATURE)
            .keyID(UUID.randomUUID().toString())
            .build();
    System.out.println(jwk.toRSAKey());
    System.out.println(jwk.toJSONString());
}
 
Example #28
Source File: JwkSetEndpoint.java    From syhthems-platform with MIT License 5 votes vote down vote up
@GetMapping("/.well-known/jwks.json")
@ResponseBody
public Map<String, Object> getKey(Principal principal) {
    RSAPublicKey publicKey = (RSAPublicKey) this.keyPair.getPublic();
    RSAKey key = new RSAKey.Builder(publicKey).build();
    return new JWKSet(key).toJSONObject();
}
 
Example #29
Source File: JWTTokenGenerator.java    From micro-integrator with Apache License 2.0 5 votes vote down vote up
/**
 * Builds RSAKey with generated key pair
 *
 * @param jwtTokenDTO      JWT Token info object
 * @param keyPairGenerator keyPairGenerator
 * @return RSAKey built RSA Key which can be used to sign
 */
private RSAKey generateRSAKey(JWTTokenInfoDTO jwtTokenDTO, KeyPairGenerator keyPairGenerator) {

    KeyPair keyPair = keyPairGenerator.generateKeyPair();
    jwtTokenDTO.setGeneratedKeyPair(keyPair);
    RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
    RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
    RSAKey.Builder builder = new RSAKey.Builder(publicKey)
            .privateKey(privateKey);
    RSAKey rsaKey = builder.keyID(jwtTokenDTO.getToken()).build();
    jwtTokenDTO.setRsaKey(rsaKey);
    return rsaKey;
}
 
Example #30
Source File: JWTTokenGenerator.java    From micro-integrator with Apache License 2.0 5 votes vote down vote up
/**
 * Builds RSAKey using key store.
 *
 * @param jwtTokenDTO      token info object
 * @param keyPairGenerator key pair generator
 * @return RSAKey built RSA Key which can be used to sign
 * @throws Exception
 */
private RSAKey generateRSAKeyWithKeyStore(JWTTokenInfoDTO jwtTokenDTO, KeyPairGenerator keyPairGenerator) throws Exception {

    KeyStore keystore = KeyStoreManager.getInstance(AppDeployerUtils.getTenantId()).getPrimaryKeyStore();
    KeyPair keyPair = keyPairGenerator.generateKeyPair();
    RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
    RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
    RSAKey.Builder builder = new RSAKey.Builder(publicKey)
            .privateKey(privateKey).keyStore(keystore);
    return builder.keyID(jwtTokenDTO.getToken()).build();
}