Search in sources :

Example 41 with RSASigner

use of io.jans.as.model.jws.RSASigner in project jans by JanssenProject.

the class DeviceAuthzFlowHttpTest method verifyIdToken.

private void verifyIdToken(String idToken) throws InvalidJwtException, UnrecoverableKeyException, NoSuchAlgorithmException, KeyStoreException, KeyManagementException {
    Jwt jwt = Jwt.parse(idToken);
    assertJwtStandarClaimsNotNull(jwt, false, false);
    assertNotNull(jwt.getClaims().getClaimAsString(JwtClaimName.OX_OPENID_CONNECT_VERSION));
    RSAPublicKey publicKey = JwkClient.getRSAPublicKey(jwksUri, jwt.getHeader().getClaimAsString(JwtHeaderName.KEY_ID), clientEngine(true));
    RSASigner rsaSigner = new RSASigner(SignatureAlgorithm.RS256, publicKey);
    assertTrue(rsaSigner.validate(jwt));
}
Also used : RSAPublicKey(io.jans.as.model.crypto.signature.RSAPublicKey) Jwt(io.jans.as.model.jwt.Jwt) RSASigner(io.jans.as.model.jws.RSASigner)

Example 42 with RSASigner

use of io.jans.as.model.jws.RSASigner in project jans by JanssenProject.

the class TokenRevocationTest method requestTokenRevocationOptionalTokenTypeHint.

@Parameters({ "userId", "userSecret", "redirectUris", "redirectUri", "sectorIdentifierUri" })
@Test
public void requestTokenRevocationOptionalTokenTypeHint(final String userId, final String userSecret, final String redirectUris, final String redirectUri, final String sectorIdentifierUri) throws Exception {
    showTitle("requestTokenRevocationOptionalTokenTypeHint");
    List<ResponseType> responseTypes = Arrays.asList(ResponseType.CODE, ResponseType.ID_TOKEN);
    List<String> scopes = Arrays.asList("openid", "profile", "address", "email", "phone", "user_name");
    // 1. Register client
    RegisterResponse registerResponse = registerClient(redirectUris, responseTypes, scopes, sectorIdentifierUri);
    String clientId = registerResponse.getClientId();
    String clientSecret = registerResponse.getClientSecret();
    // 2. Request authorization and receive the authorization code.
    String nonce = UUID.randomUUID().toString();
    AuthorizationResponse authorizationResponse = requestAuthorization(userId, userSecret, redirectUri, responseTypes, scopes, clientId, nonce);
    String scope = authorizationResponse.getScope();
    String authorizationCode = authorizationResponse.getCode();
    String idToken = authorizationResponse.getIdToken();
    // 3. Request access token using the authorization code.
    TokenRequest tokenRequest = new TokenRequest(GrantType.AUTHORIZATION_CODE);
    tokenRequest.setCode(authorizationCode);
    tokenRequest.setRedirectUri(redirectUri);
    tokenRequest.setAuthUsername(clientId);
    tokenRequest.setAuthPassword(clientSecret);
    tokenRequest.setAuthenticationMethod(AuthenticationMethod.CLIENT_SECRET_BASIC);
    TokenClient tokenClient1 = new TokenClient(tokenEndpoint);
    tokenClient1.setRequest(tokenRequest);
    TokenResponse tokenResponse1 = tokenClient1.exec();
    showClient(tokenClient1);
    assertTokenResponseOk(tokenResponse1, true, false);
    String refreshToken = tokenResponse1.getRefreshToken();
    // 4. Validate id_token
    Jwt jwt = Jwt.parse(idToken);
    assertJwtStandarClaimsNotNull(jwt, false);
    assertNotNull(jwt.getClaims().getClaimAsString(JwtClaimName.CODE_HASH));
    assertNotNull(jwt.getClaims().getClaimAsString(JwtClaimName.OX_OPENID_CONNECT_VERSION));
    RSAPublicKey publicKey = JwkClient.getRSAPublicKey(jwksUri, jwt.getHeader().getClaimAsString(JwtHeaderName.KEY_ID));
    RSASigner rsaSigner = new RSASigner(SignatureAlgorithm.RS256, publicKey);
    assertTrue(rsaSigner.validate(jwt));
    // 5. Request new access token using the refresh token.
    TokenClient tokenClient2 = new TokenClient(tokenEndpoint);
    TokenResponse tokenResponse2 = tokenClient2.execRefreshToken(scope, refreshToken, clientId, clientSecret);
    showClient(tokenClient2);
    assertTokenResponseOk(tokenResponse2, true, false);
    assertNotNull(tokenResponse2.getScope(), "The scope is null");
    String accessToken = tokenResponse2.getAccessToken();
    String refreshToken2 = tokenResponse2.getRefreshToken();
    // 6. Request user info
    UserInfoClient userInfoClient1 = new UserInfoClient(userInfoEndpoint);
    UserInfoResponse userInfoResponse1 = userInfoClient1.execUserInfo(accessToken);
    showClient(userInfoClient1);
    assertUserInfoBasicMinimumResponseOk(userInfoResponse1, 200);
    assertUserInfoPersonalDataNotNull(userInfoResponse1);
    assertNotNull(userInfoResponse1.getClaim(JwtClaimName.BIRTHDATE));
    assertNotNull(userInfoResponse1.getClaim(JwtClaimName.GENDER));
    assertNotNull(userInfoResponse1.getClaim(JwtClaimName.MIDDLE_NAME));
    assertNotNull(userInfoResponse1.getClaim(JwtClaimName.NICKNAME));
    assertNotNull(userInfoResponse1.getClaim(JwtClaimName.PREFERRED_USERNAME));
    assertNotNull(userInfoResponse1.getClaim(JwtClaimName.PROFILE));
    assertNotNull(userInfoResponse1.getClaim(JwtClaimName.WEBSITE));
    assertNotNull(userInfoResponse1.getClaim(JwtClaimName.EMAIL_VERIFIED));
    assertNotNull(userInfoResponse1.getClaim(JwtClaimName.PHONE_NUMBER));
    assertNotNull(userInfoResponse1.getClaim(JwtClaimName.PHONE_NUMBER_VERIFIED));
    assertNotNull(userInfoResponse1.getClaim(JwtClaimName.ADDRESS));
    assertNotNull(userInfoResponse1.getClaim(JwtClaimName.USER_NAME));
    assertNull(userInfoResponse1.getClaim("org_name"));
    assertNull(userInfoResponse1.getClaim("work_phone"));
    // 7. Request refresh token revocation
    TokenRevocationRequest tokenRevocationRequest1 = new TokenRevocationRequest();
    tokenRevocationRequest1.setToken(refreshToken2);
    tokenRevocationRequest1.setAuthUsername(clientId);
    tokenRevocationRequest1.setAuthPassword(clientSecret);
    TokenRevocationClient tokenRevocationClient1 = new TokenRevocationClient(tokenRevocationEndpoint);
    tokenRevocationClient1.setRequest(tokenRevocationRequest1);
    TokenRevocationResponse tokenRevocationResponse1 = tokenRevocationClient1.exec();
    showClient(tokenRevocationClient1);
    assertEquals(tokenRevocationResponse1.getStatus(), 200, "Unexpected response code: " + tokenRevocationResponse1.getStatus());
    // 8. Request new access token using the revoked refresh token should fail.
    TokenClient tokenClient3 = new TokenClient(tokenEndpoint);
    TokenResponse tokenResponse3 = tokenClient3.execRefreshToken(scope, refreshToken2, clientId, clientSecret);
    showClient(tokenClient3);
    assertEquals(tokenResponse3.getStatus(), 400, "Unexpected response code: " + tokenResponse2.getStatus());
    assertNotNull(tokenResponse3.getEntity(), "The entity is null");
    assertNotNull(tokenResponse3.getErrorType(), "The error type is null");
    assertNotNull(tokenResponse3.getErrorDescription(), "The error description is null");
    // 9. Request token revocation
    TokenRevocationRequest tokenRevocationRequest2 = new TokenRevocationRequest();
    tokenRevocationRequest2.setToken(accessToken);
    tokenRevocationRequest2.setAuthUsername(clientId);
    tokenRevocationRequest2.setAuthPassword(clientSecret);
    TokenRevocationClient tokenRevocationClient2 = new TokenRevocationClient(tokenRevocationEndpoint);
    tokenRevocationClient2.setRequest(tokenRevocationRequest2);
    TokenRevocationResponse tokenRevocationResponse2 = tokenRevocationClient2.exec();
    showClient(tokenRevocationClient2);
    assertEquals(tokenRevocationResponse2.getStatus(), 200, "Unexpected response code: " + tokenRevocationResponse2.getStatus());
    // 10. Request user info with the revoked access token should fail
    UserInfoClient userInfoClient2 = new UserInfoClient(userInfoEndpoint);
    UserInfoResponse userInfoResponse2 = userInfoClient2.execUserInfo(accessToken);
    showClient(userInfoClient2);
    assertEquals(userInfoResponse2.getStatus(), 401, "Unexpected response code: " + userInfoResponse2.getStatus());
    assertNotNull(userInfoResponse2.getErrorType(), "Unexpected result: errorType not found");
    assertNotNull(userInfoResponse2.getErrorDescription(), "Unexpected result: errorDescription not found");
}
Also used : Jwt(io.jans.as.model.jwt.Jwt) TokenRevocationRequest(io.jans.as.client.TokenRevocationRequest) TokenRevocationClient(io.jans.as.client.TokenRevocationClient) UserInfoClient(io.jans.as.client.UserInfoClient) ResponseType(io.jans.as.model.common.ResponseType) AuthorizationResponse(io.jans.as.client.AuthorizationResponse) RegisterResponse(io.jans.as.client.RegisterResponse) TokenResponse(io.jans.as.client.TokenResponse) RSAPublicKey(io.jans.as.model.crypto.signature.RSAPublicKey) RSASigner(io.jans.as.model.jws.RSASigner) TokenRequest(io.jans.as.client.TokenRequest) UserInfoResponse(io.jans.as.client.UserInfoResponse) TokenClient(io.jans.as.client.TokenClient) TokenRevocationResponse(io.jans.as.client.TokenRevocationResponse) Parameters(org.testng.annotations.Parameters) Test(org.testng.annotations.Test) BaseTest(io.jans.as.client.BaseTest)

Example 43 with RSASigner

use of io.jans.as.model.jws.RSASigner in project jans by JanssenProject.

the class BackchannelAuthorizeRestWebServiceImpl method requestBackchannelAuthorizationPost.

@Override
public Response requestBackchannelAuthorizationPost(String clientId, String scope, String clientNotificationToken, String acrValues, String loginHintToken, String idTokenHint, String loginHint, String bindingMessage, String userCodeParam, Integer requestedExpiry, String request, String requestUri, HttpServletRequest httpRequest, HttpServletResponse httpResponse, SecurityContext securityContext) {
    // it may be encoded
    scope = ServerUtil.urlDecode(scope);
    OAuth2AuditLog oAuth2AuditLog = new OAuth2AuditLog(ServerUtil.getIpAddress(httpRequest), Action.BACKCHANNEL_AUTHENTICATION);
    oAuth2AuditLog.setClientId(clientId);
    oAuth2AuditLog.setScope(scope);
    // ATTENTION : please do not add more parameter in this debug method because it will not work with Seam 2.2.2.Final,
    // there is limit of 10 parameters (hardcoded), see: org.jboss.seam.core.Interpolator#interpolate
    log.debug("Attempting to request backchannel authorization: " + "clientId = {}, scope = {}, clientNotificationToken = {}, acrValues = {}, loginHintToken = {}, " + "idTokenHint = {}, loginHint = {}, bindingMessage = {}, userCodeParam = {}, requestedExpiry = {}, " + "request= {}", clientId, scope, clientNotificationToken, acrValues, loginHintToken, idTokenHint, loginHint, bindingMessage, userCodeParam, requestedExpiry, request);
    log.debug("Attempting to request backchannel authorization: " + "isSecure = {}", securityContext.isSecure());
    errorResponseFactory.validateComponentEnabled(ComponentType.CIBA);
    Response.ResponseBuilder builder = Response.ok();
    SessionClient sessionClient = identity.getSessionClient();
    Client client = null;
    if (sessionClient != null) {
        client = sessionClient.getClient();
    }
    if (client == null) {
        // 401
        builder = Response.status(Response.Status.UNAUTHORIZED.getStatusCode());
        builder.entity(errorResponseFactory.getErrorAsJson(INVALID_CLIENT));
        return builder.build();
    }
    if (!cibaRequestService.hasCibaCompatibility(client)) {
        // 401
        builder = Response.status(Response.Status.BAD_REQUEST.getStatusCode());
        builder.entity(errorResponseFactory.getErrorAsJson(INVALID_REQUEST));
        return builder.build();
    }
    List<String> scopes = new ArrayList<>();
    if (StringHelper.isNotEmpty(scope)) {
        Set<String> grantedScopes = scopeChecker.checkScopesPolicy(client, scope);
        scopes.addAll(grantedScopes);
    }
    JwtAuthorizationRequest jwtRequest = null;
    if (StringUtils.isNotBlank(request) || StringUtils.isNotBlank(requestUri)) {
        jwtRequest = JwtAuthorizationRequest.createJwtRequest(request, requestUri, client, null, cryptoProvider, appConfiguration);
        if (jwtRequest == null) {
            log.error("The JWT couldn't be processed");
            // 400
            builder = Response.status(Response.Status.BAD_REQUEST.getStatusCode());
            builder.entity(errorResponseFactory.getErrorAsJson(INVALID_REQUEST));
            throw new WebApplicationException(builder.build());
        }
        authorizeRestWebServiceValidator.validateCibaRequestObject(jwtRequest, client.getClientId());
        // JWT wins
        if (!jwtRequest.getScopes().isEmpty()) {
            scopes.addAll(scopeChecker.checkScopesPolicy(client, jwtRequest.getScopes()));
        }
        if (StringUtils.isNotBlank(jwtRequest.getClientNotificationToken())) {
            clientNotificationToken = jwtRequest.getClientNotificationToken();
        }
        if (StringUtils.isNotBlank(jwtRequest.getAcrValues())) {
            acrValues = jwtRequest.getAcrValues();
        }
        if (StringUtils.isNotBlank(jwtRequest.getLoginHintToken())) {
            loginHintToken = jwtRequest.getLoginHintToken();
        }
        if (StringUtils.isNotBlank(jwtRequest.getIdTokenHint())) {
            idTokenHint = jwtRequest.getIdTokenHint();
        }
        if (StringUtils.isNotBlank(jwtRequest.getLoginHint())) {
            loginHint = jwtRequest.getLoginHint();
        }
        if (StringUtils.isNotBlank(jwtRequest.getBindingMessage())) {
            bindingMessage = jwtRequest.getBindingMessage();
        }
        if (StringUtils.isNotBlank(jwtRequest.getUserCode())) {
            userCodeParam = jwtRequest.getUserCode();
        }
        if (jwtRequest.getRequestedExpiry() != null) {
            requestedExpiry = jwtRequest.getRequestedExpiry();
        } else if (jwtRequest.getExp() != null) {
            requestedExpiry = Math.toIntExact(jwtRequest.getExp() - System.currentTimeMillis() / 1000);
        }
    }
    if (appConfiguration.isFapi() && jwtRequest == null) {
        // 400
        builder = Response.status(Response.Status.BAD_REQUEST.getStatusCode());
        builder.entity(errorResponseFactory.getErrorAsJson(INVALID_REQUEST));
        return builder.build();
    }
    User user = null;
    try {
        if (Strings.isNotBlank(loginHint)) {
            // login_hint
            user = userService.getUniqueUserByAttributes(appConfiguration.getBackchannelLoginHintClaims(), loginHint);
        } else if (Strings.isNotBlank(idTokenHint)) {
            // id_token_hint
            AuthorizationGrant authorizationGrant = authorizationGrantList.getAuthorizationGrantByIdToken(idTokenHint);
            if (authorizationGrant == null) {
                // 400
                builder = Response.status(Response.Status.BAD_REQUEST.getStatusCode());
                builder.entity(errorResponseFactory.getErrorAsJson(UNKNOWN_USER_ID));
                return builder.build();
            }
            user = authorizationGrant.getUser();
        }
        if (Strings.isNotBlank(loginHintToken)) {
            // login_hint_token
            Jwt jwt = Jwt.parse(loginHintToken);
            SignatureAlgorithm algorithm = jwt.getHeader().getSignatureAlgorithm();
            String keyId = jwt.getHeader().getKeyId();
            if (algorithm == null || Strings.isBlank(keyId)) {
                // 400
                builder = Response.status(Response.Status.BAD_REQUEST.getStatusCode());
                builder.entity(errorResponseFactory.getErrorAsJson(UNKNOWN_USER_ID));
                return builder.build();
            }
            boolean validSignature = false;
            if (algorithm.getFamily() == AlgorithmFamily.RSA) {
                RSAPublicKey publicKey = JwkClient.getRSAPublicKey(client.getJwksUri(), keyId);
                RSASigner rsaSigner = new RSASigner(algorithm, publicKey);
                validSignature = rsaSigner.validate(jwt);
            } else if (algorithm.getFamily() == AlgorithmFamily.EC) {
                ECDSAPublicKey publicKey = JwkClient.getECDSAPublicKey(client.getJwksUri(), keyId);
                ECDSASigner ecdsaSigner = new ECDSASigner(algorithm, publicKey);
                validSignature = ecdsaSigner.validate(jwt);
            }
            if (!validSignature) {
                // 400
                builder = Response.status(Response.Status.BAD_REQUEST.getStatusCode());
                builder.entity(errorResponseFactory.getErrorAsJson(UNKNOWN_USER_ID));
                return builder.build();
            }
            JSONObject subject = jwt.getClaims().getClaimAsJSON("subject");
            if (subject == null || !subject.has("subject_type") || !subject.has(subject.getString("subject_type"))) {
                // 400
                builder = Response.status(Response.Status.BAD_REQUEST.getStatusCode());
                builder.entity(errorResponseFactory.getErrorAsJson(UNKNOWN_USER_ID));
                return builder.build();
            }
            String subjectTypeKey = subject.getString("subject_type");
            String subjectTypeValue = subject.getString(subjectTypeKey);
            user = userService.getUniqueUserByAttributes(appConfiguration.getBackchannelLoginHintClaims(), subjectTypeValue);
        }
    } catch (InvalidJwtException e) {
        log.error(e.getMessage(), e);
    } catch (JSONException e) {
        log.error(e.getMessage(), e);
    }
    if (user == null) {
        // 400
        builder = Response.status(Response.Status.BAD_REQUEST.getStatusCode());
        builder.entity(errorResponseFactory.getErrorAsJson(UNKNOWN_USER_ID));
        return builder.build();
    }
    try {
        String userCode = (String) user.getAttribute("jansBackchannelUsrCode", true, false);
        DefaultErrorResponse cibaAuthorizeParamsValidation = cibaAuthorizeParamsValidatorService.validateParams(scopes, clientNotificationToken, client.getBackchannelTokenDeliveryMode(), loginHintToken, idTokenHint, loginHint, bindingMessage, client.getBackchannelUserCodeParameter(), userCodeParam, userCode, requestedExpiry);
        if (cibaAuthorizeParamsValidation != null) {
            builder = Response.status(cibaAuthorizeParamsValidation.getStatus());
            builder.entity(errorResponseFactory.errorAsJson(cibaAuthorizeParamsValidation.getType(), cibaAuthorizeParamsValidation.getReason()));
            return builder.build();
        }
        String deviceRegistrationToken = (String) user.getAttribute("jansBackchannelDeviceRegistrationTkn", true, false);
        if (deviceRegistrationToken == null) {
            // 401
            builder = Response.status(Response.Status.UNAUTHORIZED.getStatusCode());
            builder.entity(errorResponseFactory.getErrorAsJson(UNAUTHORIZED_END_USER_DEVICE));
            return builder.build();
        }
        int expiresIn = requestedExpiry != null ? requestedExpiry : appConfiguration.getBackchannelAuthenticationResponseExpiresIn();
        Integer interval = client.getBackchannelTokenDeliveryMode() == BackchannelTokenDeliveryMode.PUSH ? null : appConfiguration.getBackchannelAuthenticationResponseInterval();
        long currentTime = new Date().getTime();
        CibaRequestCacheControl cibaRequestCacheControl = new CibaRequestCacheControl(user, client, expiresIn, scopes, clientNotificationToken, bindingMessage, currentTime, acrValues);
        cibaRequestService.save(cibaRequestCacheControl, expiresIn);
        String authReqId = cibaRequestCacheControl.getAuthReqId();
        // Notify End-User to obtain Consent/Authorization
        cibaEndUserNotificationService.notifyEndUser(cibaRequestCacheControl.getScopesAsString(), cibaRequestCacheControl.getAcrValues(), authReqId, deviceRegistrationToken);
        builder.entity(getJSONObject(authReqId, expiresIn, interval).toString(4).replace("\\/", "/"));
        builder.type(MediaType.APPLICATION_JSON_TYPE);
        builder.cacheControl(ServerUtil.cacheControl(true, false));
    } catch (JSONException e) {
        builder = Response.status(400);
        builder.entity(errorResponseFactory.getErrorAsJson(INVALID_REQUEST));
        log.error(e.getMessage(), e);
    } catch (InvalidClaimException e) {
        builder = Response.status(400);
        builder.entity(errorResponseFactory.getErrorAsJson(INVALID_REQUEST));
        log.error(e.getMessage(), e);
    }
    applicationAuditLogger.sendMessage(oAuth2AuditLog);
    return builder.build();
}
Also used : InvalidJwtException(io.jans.as.model.exception.InvalidJwtException) User(io.jans.as.common.model.common.User) WebApplicationException(javax.ws.rs.WebApplicationException) SessionClient(io.jans.as.server.model.session.SessionClient) OAuth2AuditLog(io.jans.as.server.model.audit.OAuth2AuditLog) ArrayList(java.util.ArrayList) CibaRequestCacheControl(io.jans.as.server.model.common.CibaRequestCacheControl) SignatureAlgorithm(io.jans.as.model.crypto.signature.SignatureAlgorithm) InvalidClaimException(io.jans.as.model.exception.InvalidClaimException) RSAPublicKey(io.jans.as.model.crypto.signature.RSAPublicKey) RSASigner(io.jans.as.model.jws.RSASigner) JwtAuthorizationRequest(io.jans.as.server.model.authorize.JwtAuthorizationRequest) JwkClient(io.jans.as.client.JwkClient) Client(io.jans.as.common.model.registration.Client) SessionClient(io.jans.as.server.model.session.SessionClient) DefaultErrorResponse(io.jans.as.model.error.DefaultErrorResponse) AuthorizationGrant(io.jans.as.server.model.common.AuthorizationGrant) ECDSAPublicKey(io.jans.as.model.crypto.signature.ECDSAPublicKey) ECDSASigner(io.jans.as.model.jws.ECDSASigner) Jwt(io.jans.as.model.jwt.Jwt) JSONException(org.json.JSONException) Date(java.util.Date) Response(javax.ws.rs.core.Response) DefaultErrorResponse(io.jans.as.model.error.DefaultErrorResponse) HttpServletResponse(javax.servlet.http.HttpServletResponse) JSONObject(org.json.JSONObject)

Example 44 with RSASigner

use of io.jans.as.model.jws.RSASigner in project jans by JanssenProject.

the class SignatureTest method generateRS384Keys.

@Test
public void generateRS384Keys() throws Exception {
    showTitle("TEST: generateRS384Keys");
    KeyFactory<RSAPrivateKey, RSAPublicKey> keyFactory = new RSAKeyFactory(SignatureAlgorithm.RS384, "CN=Test CA Certificate");
    Key<RSAPrivateKey, RSAPublicKey> key = keyFactory.getKey();
    RSAPrivateKey privateKey = key.getPrivateKey();
    RSAPublicKey publicKey = key.getPublicKey();
    Certificate certificate = key.getCertificate();
    System.out.println(key);
    String signingInput = "Hello World!";
    RSASigner rsaSigner1 = new RSASigner(SignatureAlgorithm.RS384, privateKey);
    String signature = rsaSigner1.generateSignature(signingInput);
    RSASigner rsaSigner2 = new RSASigner(SignatureAlgorithm.RS384, publicKey);
    assertTrue(rsaSigner2.validateSignature(signingInput, signature));
    RSASigner rsaSigner3 = new RSASigner(SignatureAlgorithm.RS384, certificate);
    assertTrue(rsaSigner3.validateSignature(signingInput, signature));
}
Also used : RSAKeyFactory(io.jans.as.model.crypto.signature.RSAKeyFactory) RSAPublicKey(io.jans.as.model.crypto.signature.RSAPublicKey) RSASigner(io.jans.as.model.jws.RSASigner) RSAPrivateKey(io.jans.as.model.crypto.signature.RSAPrivateKey) Certificate(io.jans.as.model.crypto.Certificate) Test(org.testng.annotations.Test) BaseTest(io.jans.as.server.BaseTest)

Example 45 with RSASigner

use of io.jans.as.model.jws.RSASigner in project jans by JanssenProject.

the class SignatureTest method generateRS256Keys.

@Test
public void generateRS256Keys() throws Exception {
    showTitle("TEST: generateRS256Keys");
    KeyFactory<RSAPrivateKey, RSAPublicKey> keyFactory = new RSAKeyFactory(SignatureAlgorithm.RS256, "CN=Test CA Certificate");
    Key<RSAPrivateKey, RSAPublicKey> key = keyFactory.getKey();
    RSAPrivateKey privateKey = key.getPrivateKey();
    RSAPublicKey publicKey = key.getPublicKey();
    Certificate certificate = key.getCertificate();
    System.out.println(key);
    String signingInput = "Hello World!";
    RSASigner rsaSigner1 = new RSASigner(SignatureAlgorithm.RS256, privateKey);
    String signature = rsaSigner1.generateSignature(signingInput);
    RSASigner rsaSigner2 = new RSASigner(SignatureAlgorithm.RS256, publicKey);
    assertTrue(rsaSigner2.validateSignature(signingInput, signature));
    RSASigner rsaSigner3 = new RSASigner(SignatureAlgorithm.RS256, certificate);
    assertTrue(rsaSigner3.validateSignature(signingInput, signature));
}
Also used : RSAKeyFactory(io.jans.as.model.crypto.signature.RSAKeyFactory) RSAPublicKey(io.jans.as.model.crypto.signature.RSAPublicKey) RSASigner(io.jans.as.model.jws.RSASigner) RSAPrivateKey(io.jans.as.model.crypto.signature.RSAPrivateKey) Certificate(io.jans.as.model.crypto.Certificate) Test(org.testng.annotations.Test) BaseTest(io.jans.as.server.BaseTest)

Aggregations

RSASigner (io.jans.as.model.jws.RSASigner)107 RSAPublicKey (io.jans.as.model.crypto.signature.RSAPublicKey)106 Jwt (io.jans.as.model.jwt.Jwt)100 Test (org.testng.annotations.Test)94 AuthorizationResponse (io.jans.as.client.AuthorizationResponse)92 BaseTest (io.jans.as.client.BaseTest)90 RegisterResponse (io.jans.as.client.RegisterResponse)90 ResponseType (io.jans.as.model.common.ResponseType)90 Parameters (org.testng.annotations.Parameters)89 AuthorizationRequest (io.jans.as.client.AuthorizationRequest)86 RegisterClient (io.jans.as.client.RegisterClient)83 RegisterRequest (io.jans.as.client.RegisterRequest)83 AuthorizeClient (io.jans.as.client.AuthorizeClient)53 UserInfoClient (io.jans.as.client.UserInfoClient)49 UserInfoResponse (io.jans.as.client.UserInfoResponse)49 JwtAuthorizationRequest (io.jans.as.client.model.authorize.JwtAuthorizationRequest)40 AuthCryptoProvider (io.jans.as.model.crypto.AuthCryptoProvider)25 TokenClient (io.jans.as.client.TokenClient)24 TokenResponse (io.jans.as.client.TokenResponse)24 Claim (io.jans.as.client.model.authorize.Claim)24