Encrypt resolved username.

@param principal         the principal
@param service           the service
@param registeredService the registered service
@param username          the username
@return the encrypted username or null
977315
protected String encryptResolvedUsername(final Principal principal, final Service service, final RegisteredService registeredService, final String username) {
        val applicationContext = ApplicationContextProvider.getApplicationContext();
        val cipher = applicationContext.getBean("registeredServiceCipherExecutor", RegisteredServiceCipherExecutor.class);
        return cipher.encode(username, Optional.of(registeredService));
    }
826772
def get_password(self, service, username):
        
        init_part = self._keyring.get_password(service, username)
        if init_part:
            parts = [init_part]
            i = 1
            while True:
                next_part = self._keyring.get_password(
                    service,
                    '%s{{part_%d}}' % (username, i))
                if next_part:
                    parts.append(next_part)
                    i += 1
                else:
                    break
            return ''.join(parts)
        return None
483365
public Service buildService(final OAuthRegisteredService registeredService, final J2EContext context, final boolean useServiceHeader) {
        var id = StringUtils.EMPTY;
        if (useServiceHeader) {
            id = OAuth20Utils.getServiceRequestHeaderIfAny(context.getRequest());
            LOGGER.debug("Located service based on request header is [{}]", id);
        }
        if (StringUtils.isBlank(id)) {
            id = registeredService.getClientId();
        }
        return webApplicationServiceServiceFactory.createService(id);
    }
174232
public static synchronized boolean pushSubject(String username) {
        if (securityService == null || username == null) {
            if (tc.isDebugEnabled()) {
                Tr.debug(tc, "returning false because user or securityService is null,"
                        + " user= " + username + " secsvc= " + securityService);
            }
            return false;
        }
        AuthenticationService authenticationService = securityService.getAuthenticationService();
        Subject tempSubject = new Subject();

        Hashtable<String, Object> hashtable = new Hashtable<String, Object>();
        if (!authenticationService.isAllowHashTableLoginWithIdOnly()) {
            hashtable.put(AuthenticationConstants.INTERNAL_ASSERTION_KEY, Boolean.TRUE);
        }
        hashtable.put("com.ibm.wsspi.security.cred.userId", username);
        tempSubject.getPublicCredentials().add(hashtable);
        try {
            Subject new_subject = authenticationService.authenticate(JaasLoginConfigConstants.SYSTEM_WEB_INBOUND, tempSubject);
            return setRunAsSubject(new_subject);

        } catch (AuthenticationException e) {
            FFDCFilter.processException(e,
                    TokenPropagationHelper.class.getName(), "pushSubject",
                    new Object[] { username });
            Tr.error(tc, "ERROR_AUTHENTICATE", new Object[] { e.getMessage() }); // CWWKS6103E
            return false;
        } catch (Exception e) {
            FFDCFilter.processException(e,
                    TokenPropagationHelper.class.getName(), "pushSubject",
                    new Object[] { username });
            return false;
        }
    }
121936
public Principal authenticate(String username, char password[]) 
    throws NamingException
	{
		DirContext ctx = null;
		try
		{
			String userDN = toDN(username);
			ctx = initContext(userDN, password);

			return new X500Principal(userDN);
		}
		finally
		{
			if(ctx != null)
				try{ ctx.close(); } catch(Exception e){e.printStackTrace();}
		}
	}
1184033
private SecurityContext getUserContext(final RepositoryObject obj) {

		final String userId = obj.getUserId();
		Principal principal = null;

		if (userId != null) {

			final App app = StructrApp.getInstance();

			try (final Tx tx = app.tx()) {

				// TODO: change this, userId is currently the name of a user,
				//       WITHOUT ANY AUTHENTICATION.
				principal = app.nodeQuery(Principal.class).and(Principal.name, userId).getFirst();
				tx.success();

			} catch (FrameworkException fex) {
				logger.warn("", fex);
			}

		} else {

			System.out.println("Object without userId!");
		}

		// return user
		if (principal != null) {
			return SecurityContext.getInstance(principal, AccessMode.Backend);
		}

		return SecurityContext.getSuperUserInstance();
	}
282045
@Override
    public Subject authenticate(String username, @Sensitive String password) throws AuthenticationException {
        AuthenticationData authenticationData = createAuthenticationData(username, password);
        return authenticationService.authenticate(jaasEntryName, authenticationData, null);
    }
94399
public static Subject generateSecuritySubject(String jassLoginConfig, String username, String password) throws LoginException {
  	  
        LoginContext loginCtx = null;
      
        try {
      
            // "Client" references the JAAS configuration in the jaas.conf file.
            loginCtx = new LoginContext(jassLoginConfig, new Krb5TokenUtils.LoginCallbackHandler(username, password));
            loginCtx.login();
 
            log.debug(" : Krb5Token Kerberos login succeeded against user: %s", username);
      
            return loginCtx.getSubject();
        }
        catch(LoginException e) {
            log.debug(" : Krb5Token Kerberos login failed against user: %s", username);
            throw e;
        }
    }
57513
public static String buildKey(final RegisteredService service) {
        return service.getId() + ";" + service.getName() + ';' + service.getServiceId();
    }
87724
protected RegisteredService resolveRegisteredServiceInRequestContext(final RequestContext requestContext) {
        val resolvedService = resolveServiceFromAuthenticationRequest(requestContext);
        if (resolvedService != null) {
            val service = getWebflowEventResolutionConfigurationContext().getServicesManager().findServiceBy(resolvedService);
            RegisteredServiceAccessStrategyUtils.ensureServiceAccessIsAllowed(resolvedService, service);
            return service;
        }
        LOGGER.debug("Authentication request is not accompanied by a service given none is specified");
        return null;
    }
359094
def get_password(self, service, username):
        
        items = self._find_passwords(service, username)
        if not items:
            return None

        secret = items[0].secret
        return (
            secret
            if isinstance(secret, six.text_type) else
            secret.decode('utf-8')
        )
717120
protected Map<String, List<Object>> authorizeReleaseOfAllowedAttributes(final Principal principal,
                                                                            final Map<String, List<Object>> attrs,
                                                                            final RegisteredService registeredService,
                                                                            final Service selectedService) {
        val resolvedAttributes = new TreeMap<String, List<Object>>(String.CASE_INSENSITIVE_ORDER);
        resolvedAttributes.putAll(attrs);
        val attributesToRelease = new HashMap<String, List<Object>>();
        getAllowedAttributes()
            .stream()
            .filter(resolvedAttributes::containsKey)
            .forEach(attr -> {
                LOGGER.debug("Found attribute [{}] in the list of allowed attributes", attr);
                attributesToRelease.put(attr, resolvedAttributes.get(attr));
            });
        return attributesToRelease;
    }
169583
@SneakyThrows
    public User getOrCreateUser(final Principal principal) {
        val attributes = principal.getAttributes();
        if (!attributes.containsKey(this.mailAttribute)) {
            throw new IllegalArgumentException("No email address found for " + principal.getId());
        }
        if (!attributes.containsKey(this.phoneAttribute)) {
            throw new IllegalArgumentException("No phone number found for " + principal.getId());
        }

        val email = attributes.get(this.mailAttribute).get(0).toString();
        val phone = attributes.get(this.phoneAttribute).get(0).toString();
        return this.authyUsers.createUser(email, phone, this.countryCode);
    }
387020
private static Cipher initializeCipherBasedOnServicePublicKey(final PublicKey publicKey,
                                                                  final RegisteredService registeredService) {
        try {
            LOGGER.debug("Using service [{}] public key [{}] to initialize the cipher", registeredService.getServiceId(),
                registeredService.getPublicKey());

            val cipher = Cipher.getInstance(publicKey.getAlgorithm());
            cipher.init(Cipher.ENCRYPT_MODE, publicKey);
            LOGGER.debug("Initialized cipher in encrypt-mode via the public key algorithm [{}] for service [{}]",
                publicKey.getAlgorithm(), registeredService.getServiceId());
            return cipher;
        } catch (final Exception e) {
            LOGGER.warn("Cipher could not be initialized for service [{}]. Error [{}]",
                registeredService, e.getMessage());
        }
        return null;
    }
451665
def get_password(self, service, username):
        
        result = self._get_entry(self._keyring, service, username)
        if result:
            result = self._decrypt(result)
        return result
321614
public java.security.Principal getUserPrincipal()
    {
        if (WCCustomProperties.CHECK_REQUEST_OBJECT_IN_USE){
            checkRequestObjectInUse();
        }
        IWebAppSecurityCollaborator webAppSec=null;
        if (getDispatchContext()!=null && getDispatchContext().getWebApp() != null) {
            webAppSec = CollaboratorHelperImpl.getCurrentSecurityCollaborator(getDispatchContext().getWebApp());
        } else {
            webAppSec = CollaboratorHelperImpl.getCurrentSecurityCollaborator();           
        } 
            
        if (webAppSec != null) {
            if (TraceComponent.isAnyTracingEnabled()&&logger.isLoggable (Level.FINE)){  //306998.15
                logger.logp(Level.FINE, CLASS_NAME,"getUserPrincipal", "calling getUserPrincipal on " + webAppSec.getClass().getName());
            }
            return webAppSec.getUserPrincipal();
        } else {
            if (TraceComponent.isAnyTracingEnabled()&&logger.isLoggable (Level.FINE)){  //306998.15
                logger.logp(Level.FINE, CLASS_NAME,"getUserPrincipal", "returning null");
            }
            // No IWebAppSecurityCollaborator means no security, so no Principal 
            return null;
        }
    }
1311959
protected void insertPrincipalIdAsAttributeIfNeeded(final Principal principal, final Map<String, List<Object>> attributesToRelease,
                                                        final Service service, final RegisteredService registeredService) {
        if (StringUtils.isNotBlank(getPrincipalIdAttribute())) {
            LOGGER.debug("Attempting to resolve the principal id for service [{}]", registeredService.getServiceId());
            val id = registeredService.getUsernameAttributeProvider().resolveUsername(principal, service, registeredService);
            LOGGER.debug("Releasing resolved principal id [{}] as attribute [{}]", id, getPrincipalIdAttribute());
            attributesToRelease.put(getPrincipalIdAttribute(), CollectionUtils.wrapList(principal.getId()));
        }
    }