org.gluu.util.security.StringEncrypter Java Examples

The following examples show how to use org.gluu.util.security.StringEncrypter. 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: AppInitializer.java    From oxTrust with MIT License 6 votes vote down vote up
@Produces
@ApplicationScoped
public StringEncrypter getStringEncrypter() throws OxIntializationException {
	String encodeSalt = configurationFactory.getCryptoConfigurationSalt();

	if (StringHelper.isEmpty(encodeSalt)) {
		throw new OxIntializationException("Encode salt isn't defined");
	}

	try {
		StringEncrypter stringEncrypter = StringEncrypter.instance(encodeSalt);

		return stringEncrypter;
	} catch (EncryptionException ex) {
		throw new OxIntializationException("Failed to create StringEncrypter instance");
	}
}
 
Example #2
Source File: CleanerTimerTest.java    From oxAuth with MIT License 6 votes vote down vote up
private Client createClient(boolean deletable) throws StringEncrypter.EncryptionException {
    String clientsBaseDN = staticConfiguration.getBaseDn().getClients();

    String inum = inumService.generateClientInum();
    String generatedClientSecret = UUID.randomUUID().toString();

    final Client client = new Client();
    client.setDn("inum=" + inum + "," + clientsBaseDN);
    client.setClientName("Cleaner Timer Test");
    client.setClientId(inum);
    client.setClientSecret(clientService.encryptSecret(generatedClientSecret));
    client.setRegistrationAccessToken(HandleTokenFactory.generateHandleToken());
    client.setDeletable(deletable);

    final Calendar calendar = new GregorianCalendar(TimeZone.getTimeZone("UTC"));
    client.setClientIdIssuedAt(calendar.getTime());

    calendar.add(Calendar.MINUTE, 10);
    client.setExpirationDate(calendar.getTime());
    return client;
}
 
Example #3
Source File: CleanerTimerTest.java    From oxAuth with MIT License 6 votes vote down vote up
@Test
public void client_whichIsNotExpiredAndDeletable_MustNotBeRemoved() throws StringEncrypter.EncryptionException {

    // 1. create client
    final Client client = createClient(true);

    clientService.persist(client);

    // 2. client is in persistence
    assertNotNull(clientService.getClient(client.getClientId()));

    // 3. clean up
    cleanerTimer.processImpl();
    cacheService.clear();

    // 4. client is in persistence (not removed)
    assertNotNull(clientService.getClient(client.getClientId()));
}
 
Example #4
Source File: CleanerTimerTest.java    From oxAuth with MIT License 6 votes vote down vote up
@Test(enabled = false) // disabled temporarily. It works perfectly locally but fails on jenkins. Reason is unclear.
public void client_whichIsExpiredAndDeletable_MustBeRemoved() throws StringEncrypter.EncryptionException {
    // 1. create client
    final Client client = createClient(true);

    final Calendar calendar = new GregorianCalendar(TimeZone.getTimeZone("UTC"));
    client.setClientIdIssuedAt(calendar.getTime());

    calendar.add(Calendar.MONTH, -1);
    client.setExpirationDate(calendar.getTime());

    clientService.persist(client);

    // 2. client is in persistence
    assertNotNull(clientService.getClient(client.getClientId()));

    // 3. clean up
    cleanerTimer.processImpl();
    cacheService.clear();

    // 4. no client in persistence
    assertNull(clientService.getClient(client.getClientId()));
}
 
Example #5
Source File: UmaResourceServiceTest.java    From oxAuth with MIT License 6 votes vote down vote up
private Client createClient(boolean deletable) throws StringEncrypter.EncryptionException {
    String clientsBaseDN = staticConfiguration.getBaseDn().getClients();

    String inum = inumService.generateClientInum();
    String generatedClientSecret = UUID.randomUUID().toString();

    final Client client = new Client();
    client.setDn("inum=" + inum + "," + clientsBaseDN);
    client.setClientName("Cleaner Timer Test");
    client.setClientId(inum);
    client.setClientSecret(clientService.encryptSecret(generatedClientSecret));
    client.setRegistrationAccessToken(HandleTokenFactory.generateHandleToken());
    client.setDeletable(deletable);

    final Calendar calendar = new GregorianCalendar(TimeZone.getTimeZone("UTC"));
    client.setClientIdIssuedAt(calendar.getTime());

    calendar.add(Calendar.MINUTE, 10);
    client.setExpirationDate(calendar.getTime());
    return client;
}
 
Example #6
Source File: AppInitializer.java    From oxAuth with MIT License 6 votes vote down vote up
@Produces
@ApplicationScoped
public StringEncrypter getStringEncrypter() {
	String encodeSalt = configurationFactory.getCryptoConfigurationSalt();

	if (StringHelper.isEmpty(encodeSalt)) {
		throw new ConfigurationException("Encode salt isn't defined");
	}

	try {
		StringEncrypter stringEncrypter = StringEncrypter.instance(encodeSalt);

		return stringEncrypter;
	} catch (EncryptionException ex) {
		throw new ConfigurationException("Failed to create StringEncrypter instance");
	}
}
 
Example #7
Source File: ClientService.java    From oxAuth with MIT License 6 votes vote down vote up
/**
 * Authenticate client.
 *
 * @param clientId
 *            Client inum.
 * @param password
 *            Client password.
 * @return <code>true</code> if success, otherwise <code>false</code>.
 */
public boolean authenticate(String clientId, String password) {
	log.debug("Authenticating Client with LDAP: clientId = {}", clientId);
	boolean authenticated = false;

	try {
		Client client = getClient(clientId);
		if (client == null) {
			log.debug("Failed to find client = {}", clientId);
			return authenticated;
		}
		String decryptedClientSecret = decryptSecret(client.getClientSecret());
		authenticated = client != null && decryptedClientSecret != null && decryptedClientSecret.equals(password);
	} catch (StringEncrypter.EncryptionException e) {
		log.error(e.getMessage(), e);
	}

	return authenticated;
}
 
Example #8
Source File: UmaResourceServiceTest.java    From oxAuth with MIT License 5 votes vote down vote up
@Test
public void umaResource_independentFromDeletableFlag_shouldBeSearchable() throws StringEncrypter.EncryptionException {
    final Client client = createClient();

    clientService.persist(client);

    // 1. create resource
    UmaResource resource = new UmaResource();
    resource.setName("Test resource");
    resource.setScopes(Lists.newArrayList("view"));
    resource.setId(UUID.randomUUID().toString());
    resource.setDn(umaResourceService.getDnForResource(resource.getId()));
    resource.setDeletable(false);

    final Calendar calendar = Calendar.getInstance();
    resource.setCreationDate(calendar.getTime());

    umaResourceService.addResource(resource);

    // 2. resource exists
    assertNotNull(umaResourceService.getResourceById(resource.getId()));

    // 4. resource exists
    assertNotNull(umaResourceService.getResourceById(resource.getId()));

    calendar.add(Calendar.MINUTE, -10);
    resource.setExpirationDate(calendar.getTime());
    resource.setDeletable(true);

    umaResourceService.updateResource(resource, true);

    // resource exists
    assertNotNull(umaResourceService.getResourceById(resource.getId()));

    // remove it
    umaResourceService.remove(resource);
}
 
Example #9
Source File: GluuPersistenceConfiguration.java    From oxd with Apache License 2.0 5 votes vote down vote up
protected Properties preparePersistanceProperties(String cryptoConfigurationSalt) {

        Properties decryptedConnectionProperties;
        try {
            decryptedConnectionProperties = PropertiesDecrypter.decryptAllProperties(StringEncrypter.defaultInstance(), this.connectionProperties, cryptoConfigurationSalt);
        } catch (StringEncrypter.EncryptionException ex) {
            throw new ConfigurationException("Failed to decript configuration properties", ex);
        }

        return decryptedConnectionProperties;
    }
 
Example #10
Source File: LdapConfigurationService.java    From oxTrust with MIT License 5 votes vote down vote up
private String encrypt(String data) {
	try {
		return encryptionService.encrypt(data);
	} catch (StringEncrypter.EncryptionException e) {
		throw new LdapConfigurationException(e);
	}
}
 
Example #11
Source File: CleanerTimerTest.java    From oxAuth with MIT License 5 votes vote down vote up
@Test
public void umaPct_whichIsExpiredAndDeletable_MustBeRemoved() throws StringEncrypter.EncryptionException {
    final Client client = createClient();
    clientService.persist(client);

    // 1. create pct
    UmaPCT pct = umaPctService.createPct(client.getClientId());
    umaPctService.persist(pct);

    // 2. pct exists
    assertNotNull(umaPctService.getByCode(pct.getCode()));

    // 3. clean up
    cleanerTimer.processImpl();
    cacheService.clear();

    // 4. pct exists
    assertNotNull(umaPctService.getByCode(pct.getCode()));

    final Calendar calendar = Calendar.getInstance();
    calendar.add(Calendar.MINUTE, -10);
    pct.setExpirationDate(calendar.getTime());

    umaPctService.merge(pct);

    // 5. clean up
    cleanerTimer.processImpl();
    cacheService.clear();

    // 6. no pct in persistence
    assertNull(umaPctService.getByCode(pct.getCode()));
}
 
Example #12
Source File: CleanerTimerTest.java    From oxAuth with MIT License 5 votes vote down vote up
@Test
public void umaPermission_whichIsExpiredAndDeletable_MustBeRemoved() throws StringEncrypter.EncryptionException {
    final Client client = createClient();

    clientService.persist(client);

    final String ticket = UUID.randomUUID().toString();

    // 1. create permission
    UmaPermission permission = new UmaPermission();
    permission.setTicket(ticket);
    permission.setConfigurationCode(UUID.randomUUID().toString());
    permission.setResourceId(UUID.randomUUID().toString());

    umaPermissionService.addPermission(permission, client.getDn());

    // 2. permission exists
    assertNotNull(umaPermissionService.getPermissionsByTicket(ticket).get(0));

    // 3. clean up
    cleanerTimer.processImpl();
    cacheService.clear();

    // 4. permission exists
    assertNotNull(umaPermissionService.getPermissionsByTicket(ticket).get(0));

    final Calendar calendar = Calendar.getInstance();
    calendar.add(Calendar.MINUTE, -10);
    permission.setExpirationDate(calendar.getTime());

    umaPermissionService.merge(permission);

    // 5. clean up
    cleanerTimer.processImpl();
    cacheService.clear();

    // 6. no permission in persistence
    final List<UmaPermission> permissionsByTicket = umaPermissionService.getPermissionsByTicket(ticket);
    assertTrue(permissionsByTicket.isEmpty());
}
 
Example #13
Source File: CleanerTimerTest.java    From oxAuth with MIT License 5 votes vote down vote up
@Test
public void umaRpt_whichIsExpiredAndDeletable_MustBeRemoved() throws StringEncrypter.EncryptionException {
    final Client client = createClient();

    clientService.persist(client);

    // 1. create RPT
    final UmaRPT rpt = umaRptService.createRPTAndPersist(client, Lists.newArrayList());

    // 2. RPT exists
    assertNotNull(umaRptService.getRPTByCode(rpt.getNotHashedCode()));

    // 3. clean up
    cleanerTimer.processImpl();
    cacheService.clear();

    // 4. RPT exists
    assertNotNull(umaRptService.getRPTByCode(rpt.getNotHashedCode()));

    final Calendar calendar = new GregorianCalendar(TimeZone.getTimeZone("UTC"));
    calendar.add(Calendar.MINUTE, -10);
    rpt.setExpirationDate(calendar.getTime());

    umaRptService.merge(rpt);

    // 5. clean up
    cleanerTimer.processImpl();
    cacheService.clear();

    // 6. no RPT in persistence
    assertNull(umaRptService.getRPTByCode(rpt.getNotHashedCode()));
}
 
Example #14
Source File: CleanerTimerTest.java    From oxAuth with MIT License 5 votes vote down vote up
@Test
public void token_whichIsExpiredAndDeletable_MustBeRemoved() throws StringEncrypter.EncryptionException {
    final Client client = createClient();
    clientService.persist(client);

    // 1. create token
    final ClientCredentialsGrant grant = authorizationGrantList.createClientCredentialsGrant(new User(), client);
    final AccessToken accessToken = grant.createAccessToken(null, new ExecutionContext(null, null));

    // 2. token exists
    assertNotNull(grantService.getGrantByCode(accessToken.getCode()));

    // 3. clean up
    cleanerTimer.processImpl();
    cacheService.clear();

    // 4. token exists
    final TokenLdap grantLdap = grantService.getGrantByCode(accessToken.getCode());
    assertNotNull(grantLdap);

    final Calendar calendar = Calendar.getInstance();
    calendar.add(Calendar.MINUTE, -10);
    grantLdap.setExpirationDate(calendar.getTime());

    grantService.merge(grantLdap);

    // 5. clean up
    cleanerTimer.processImpl();
    cacheService.clear();

    // 6. no token in persistence
    assertNull(grantService.getGrantByCode(accessToken.getCode()));
}
 
Example #15
Source File: CleanerTimerTest.java    From oxAuth with MIT License 5 votes vote down vote up
@Test
public void u2fRequest_whichIsExpiredAndDeletable_MustBeRemoved() throws StringEncrypter.EncryptionException {
    final Client client = createClient();
    clientService.persist(client);

    // 1. create token
    String userInum = "";
    String appId = "https://testapp.com";
    final RequestMessageLdap request = u2fRegistrationService.storeRegisterRequestMessage(u2fRegistrationService.builRegisterRequestMessage(appId, userInum), userInum, userInum);

    // 2. request exists
    assertNotNull(u2fRegistrationService.getRegisterRequestMessage(request.getId()));

    // 3. clean up
    cleanerTimer.processImpl();
    cacheService.clear();

    // 4. request exists
    assertNotNull(u2fRegistrationService.getRegisterRequestMessage(request.getId()));

    final Calendar calendar = Calendar.getInstance();
    calendar.add(Calendar.MINUTE, -10);
    request.setExpirationDate(calendar.getTime());

    u2fRegistrationService.merge(request);

    // 5. clean up
    cleanerTimer.processImpl();
    cacheService.clear();

    // 6. no request in persistence
    try {
        u2fRegistrationService.getRegisterRequestMessage(request.getId());
        throw new AssertionError("No exception, expected EntryPersistenceException on find request.");
    } catch (EntryPersistenceException e) {
        // ignore
    }
}
 
Example #16
Source File: CleanerTimerTest.java    From oxAuth with MIT License 5 votes vote down vote up
@Test
public void client_whichIsExpiredAndNotDeletable_MustNotBeRemoved() throws StringEncrypter.EncryptionException {
    // 1. create client
    final Client client = createClient(false);

    try {
        final Calendar calendar = new GregorianCalendar(TimeZone.getTimeZone("UTC"));
        client.setClientIdIssuedAt(calendar.getTime());

        calendar.add(Calendar.HOUR, -1);
        client.setExpirationDate(calendar.getTime());

        clientService.persist(client);

        // 2. client is in persistence
        assertNotNull(clientService.getClient(client.getClientId()));

        // 3. clean up
        cleanerTimer.processImpl();
        cacheService.clear();

        // 4. client is in persistence (not removed)
        assertNotNull(clientService.getClient(client.getClientId()));
    } finally {
        client.setDeletable(true); // make it available for cleaner
        clientService.merge(client);

    }
}
 
Example #17
Source File: CleanerTimerTest.java    From oxAuth with MIT License 4 votes vote down vote up
@Test
public void u2fDevice_whichIsExpiredAndDeletable_MustBeRemoved() throws StringEncrypter.EncryptionException {
    final Client client = createClient();
    clientService.persist(client);

    // 1. create device
    String userInum = "";
    String appId = "https://testapp.com";
    final DeviceRegistration device = new DeviceRegistration();
    device.setStatus(DeviceRegistrationStatus.ACTIVE);
    device.setApplication(appId);
    device.setId(String.valueOf(System.currentTimeMillis()));
    device.setDn(deviceRegistrationService.getDnForU2fDevice(userInum, device.getId()));

    deviceRegistrationService.addOneStepDeviceRegistration(device);

    // 2. device exists
    assertNotNull(deviceRegistrationService.findUserDeviceRegistration(userInum, device.getId()));

    // 3. clean up
    cleanerTimer.processImpl();
    cacheService.clear();

    // 4. device exists
    assertNotNull(deviceRegistrationService.findUserDeviceRegistration(userInum, device.getId()));

    final Calendar calendar = Calendar.getInstance();
    calendar.add(Calendar.MINUTE, -10);
    device.setExpirationDate(calendar.getTime());

    deviceRegistrationService.merge(device);

    // 5. clean up
    cleanerTimer.processImpl();
    cacheService.clear();

    // 6. no device in persistence
    try {
        deviceRegistrationService.findUserDeviceRegistration(userInum, device.getId());
        throw new AssertionError("No exception, expected EntryPersistenceException on find.");
    } catch (EntryPersistenceException e) {
        // ignore
    }
}
 
Example #18
Source File: CleanerTimerTest.java    From oxAuth with MIT License 4 votes vote down vote up
@Test
public void umaResource_whichIsExpiredAndDeletable_MustBeRemoved() throws StringEncrypter.EncryptionException {
    final Client client = createClient();

    clientService.persist(client);

    // 1. create resource
    UmaResource resource = new UmaResource();
    resource.setName("Test resource");
    resource.setScopes(Lists.newArrayList("view"));
    resource.setId(UUID.randomUUID().toString());
    resource.setDn(umaResourceService.getDnForResource(resource.getId()));

    final Calendar calendar = Calendar.getInstance();
    resource.setCreationDate(calendar.getTime());

    umaResourceService.addResource(resource);

    // 2. resource exists
    assertNotNull(umaResourceService.getResourceById(resource.getId()));

    // 3. clean up
    cleanerTimer.processImpl();
    cacheService.clear();

    // 4. resource exists
    assertNotNull(umaResourceService.getResourceById(resource.getId()));

    calendar.add(Calendar.MINUTE, -10);
    resource.setExpirationDate(calendar.getTime());

    umaResourceService.updateResource(resource, true);

    // 5. clean up
    cleanerTimer.processImpl();
    cacheService.clear();

    // 6. no resource in persistence
    try {
        umaResourceService.getResourceById(resource.getId());
        throw new AssertionError("Test failed, no 404 exception");
    } catch (WebApplicationException e) {
        // we expect WebApplicationException 404 here
        assertEquals(404, e.getResponse().getStatus());
    }
}
 
Example #19
Source File: AuthenticationFilter.java    From oxTrust with MIT License 4 votes vote down vote up
public String getOAuthRedirectUrl(final HttpServletRequest request, final HttpServletResponse response) throws Exception {
    String authorizeUrl = getPropertyFromInitParams(null, Configuration.OAUTH_PROPERTY_AUTHORIZE_URL, null);
    String clientScopes = getPropertyFromInitParams(null, Configuration.OAUTH_PROPERTY_CLIENT_SCOPE, null);

    String clientId = getPropertyFromInitParams(null, Configuration.OAUTH_PROPERTY_CLIENT_ID, null);
    String clientSecret = getPropertyFromInitParams(null, Configuration.OAUTH_PROPERTY_CLIENT_PASSWORD, null);
    if (clientSecret != null) {
        try {
            clientSecret = StringEncrypter.defaultInstance().decrypt(clientSecret, Configuration.instance().getCryptoPropertyValue());
        } catch (EncryptionException ex) {
            log.error("Failed to decrypt property: " + Configuration.OAUTH_PROPERTY_CLIENT_PASSWORD, ex);
        }
    }

    String redirectUri = constructRedirectUrl(request);

    List<String> scopes = Arrays.asList(clientScopes.split(StringUtils.SPACE));
    List<ResponseType> responseTypes = Arrays.asList(ResponseType.CODE);

    String nonce = UUID.randomUUID().toString();
    String rfp = UUID.randomUUID().toString();
    String jti = UUID.randomUUID().toString();

    // Lookup for relying party ID
    final String key = request.getParameter(ExternalAuthentication.CONVERSATION_KEY);
    request.getSession().setAttribute(SESSION_CONVERSATION_KEY, key);
    ProfileRequestContext prc = ExternalAuthentication.getProfileRequestContext(key, request);

    String relyingPartyId = "";
    final RelyingPartyContext relyingPartyCtx = prc.getSubcontext(RelyingPartyContext.class);
    if (relyingPartyCtx != null) {
        relyingPartyId = relyingPartyCtx.getRelyingPartyId();
        log.info("relyingPartyId found: " + relyingPartyId);
    } else
        log.warn("No RelyingPartyContext was available");

    // JWT
    OxAuthCryptoProvider cryptoProvider = new OxAuthCryptoProvider();
    JwtState jwtState = new JwtState(SignatureAlgorithm.HS256, clientSecret, cryptoProvider);
    jwtState.setRfp(rfp);
    jwtState.setJti(jti);
    if (relyingPartyId != null && !"".equals(relyingPartyId)) {
        String additionalClaims = String.format("{relyingPartyId: '%s'}", relyingPartyId);
        jwtState.setAdditionalClaims(new JSONObject(additionalClaims));
    } else
        log.warn("No relyingPartyId was available");
    String encodedState = jwtState.getEncodedJwt();

    AuthorizationRequest authorizationRequest = new AuthorizationRequest(responseTypes, clientId, scopes, redirectUri, nonce);
    authorizationRequest.setState(encodedState);

    Cookie currentShibstateCookie = getCurrentShibstateCookie(request);
    if (currentShibstateCookie != null) {
        String requestUri = decodeCookieValue(currentShibstateCookie.getValue());
        log.debug("requestUri = \"" + requestUri + "\"");

        String authenticationMode = determineAuthenticationMode(requestUri);

        if (StringHelper.isNotEmpty(authenticationMode)) {
            log.debug("acr_values = \"" + authenticationMode + "\"");
            authorizationRequest.setAcrValues(Arrays.asList(authenticationMode));
            updateShibstateCookie(response, currentShibstateCookie, requestUri, "/" + Configuration.OXAUTH_ACR_VALUES + "/" + authenticationMode);
        }
    }

    // Store for validation in session
    final HttpSession session = request.getSession(false);
    session.setAttribute(Configuration.SESSION_AUTH_STATE, encodedState);
    session.setAttribute(Configuration.SESSION_AUTH_NONCE, nonce);

    return authorizeUrl + "?" + authorizationRequest.getQueryString();
}
 
Example #20
Source File: CleanerTimerTest.java    From oxAuth with MIT License 4 votes vote down vote up
private Client createClient() throws StringEncrypter.EncryptionException {
    return createClient(true);
}
 
Example #21
Source File: RegisterRestWebServiceImpl.java    From oxAuth with MIT License 4 votes vote down vote up
private String clientAsEntity(Client p_client) throws JSONException, StringEncrypter.EncryptionException {
    final JSONObject jsonObject = getJSONObject(p_client);
    return jsonObject.toString(4).replace("\\/", "/");
}
 
Example #22
Source File: UmaResourceServiceTest.java    From oxAuth with MIT License 4 votes vote down vote up
private Client createClient() throws StringEncrypter.EncryptionException {
    return createClient(true);
}
 
Example #23
Source File: UtilsTest.java    From oxd with Apache License 2.0 4 votes vote down vote up
@Test(enabled = false)
public void decrypt() throws StringEncrypter.EncryptionException {
    StringEncrypter stringEncrypter = StringEncrypter.instance("123456789012345678901234");
    System.out.println(stringEncrypter.decrypt(""));
}