Example usage for org.apache.commons.codec.digest DigestUtils sha256Hex

List of usage examples for org.apache.commons.codec.digest DigestUtils sha256Hex

Introduction

In this page you can find the example usage for org.apache.commons.codec.digest DigestUtils sha256Hex.

Prototype

public static String sha256Hex(String data) 

Source Link

Usage

From source file:org.trancecode.xproc.step.HashStepProcessor.java

@Override
protected void execute(final StepInput input, final StepOutput output) {
    final XdmNode sourceDocument = input.readNode(XProcPorts.SOURCE);
    final String value = input.getOptionValue(XProcOptions.VALUE);
    assert value != null;
    LOG.trace("value = {}", value);
    final String algorithm = input.getOptionValue(XProcOptions.ALGORITHM);
    assert algorithm != null;
    LOG.trace("algorithm = {}", algorithm);
    final String match = input.getOptionValue(XProcOptions.MATCH);
    assert match != null;
    LOG.trace("match = {}", match);
    final String version = input.getOptionValue(XProcOptions.VERSION);
    LOG.trace("version = {}", version);

    final String hashValue;
    if (StringUtils.equalsIgnoreCase("crc", algorithm)) {
        if ("32".equals(version) || version == null) {
            final CRC32 crc32 = new CRC32();
            crc32.update(value.getBytes());
            hashValue = Long.toHexString(crc32.getValue());
        } else {/*  w  ww  .j av  a2 s  . c o m*/
            throw XProcExceptions.xc0036(input.getLocation());
        }
    } else if (StringUtils.equalsIgnoreCase("md", algorithm)) {
        if (version == null || "5".equals(version)) {
            hashValue = DigestUtils.md5Hex(value);
        } else {
            throw XProcExceptions.xc0036(input.getLocation());
        }
    } else if (StringUtils.equalsIgnoreCase("sha", algorithm)) {
        if (version == null || "1".equals(version)) {
            hashValue = DigestUtils.shaHex(value);
        } else if ("256".equals(version)) {
            hashValue = DigestUtils.sha256Hex(value);
        } else if ("384".equals(version)) {
            hashValue = DigestUtils.sha384Hex(value);
        } else if ("512".equals(version)) {
            hashValue = DigestUtils.sha512Hex(value);
        } else {
            throw XProcExceptions.xc0036(input.getLocation());
        }
    } else {
        throw XProcExceptions.xc0036(input.getLocation());
    }

    final SaxonProcessorDelegate hashDelegate = new AbstractSaxonProcessorDelegate() {
        @Override
        public boolean startDocument(final XdmNode node, final SaxonBuilder builder) {
            return true;
        }

        @Override
        public void endDocument(final XdmNode node, final SaxonBuilder builder) {
        }

        @Override
        public EnumSet<NextSteps> startElement(final XdmNode element, final SaxonBuilder builder) {
            builder.text(hashValue);
            return EnumSet.noneOf(NextSteps.class);
        }

        @Override
        public void endElement(final XdmNode node, final SaxonBuilder builder) {
            builder.endElement();
        }

        @Override
        public void attribute(final XdmNode node, final SaxonBuilder builder) {
            builder.attribute(node.getNodeName(), hashValue);
        }

        @Override
        public void comment(final XdmNode node, final SaxonBuilder builder) {
            builder.comment(hashValue);
        }

        @Override
        public void processingInstruction(final XdmNode node, final SaxonBuilder builder) {
            builder.processingInstruction(node.getNodeName().getLocalName(), hashValue);
        }

        @Override
        public void text(final XdmNode node, final SaxonBuilder builder) {
            builder.text(hashValue);
        }
    };

    final SaxonProcessor hashProcessor = new SaxonProcessor(input.getPipelineContext().getProcessor(),
            SaxonProcessorDelegates.forXsltMatchPattern(input.getPipelineContext().getProcessor(), match,
                    input.getStep().getNode(), hashDelegate, new CopyingSaxonProcessorDelegate()));

    final XdmNode result = hashProcessor.apply(sourceDocument);
    output.writeNodes(XProcPorts.RESULT, result);
}

From source file:org.wso2.carbon.identity.gateway.context.AuthenticationContext.java

public SessionContext getSessionContext() {
    GatewayRequest identityRequest = getIdentityRequest();
    if (identityRequest instanceof AuthenticationRequest) {
        AuthenticationRequest authenticationRequest = (AuthenticationRequest) identityRequest;
        String sessionKey = authenticationRequest.getSessionKey();
        if (StringUtils.isNotBlank(sessionKey)) {
            return SessionContextCache.getInstance().get(DigestUtils.sha256Hex(sessionKey));
        }/*from  ww w.  j ava  2s  . co m*/
    }
    return null;
}

From source file:org.wso2.carbon.identity.gateway.handler.session.DefaultSessionHandler.java

@Override
public GatewayHandlerResponse updateSession(AuthenticationContext context) throws SessionHandlerException {

    GatewayRequest identityRequest = context.getIdentityRequest();
    if (identityRequest instanceof AuthenticationRequest) {
        String sessionKey = ((AuthenticationRequest) identityRequest).getSessionKey();
        String sessionKeyHash;//from ww  w  . j  a  va 2 s  .  co  m
        if (StringUtils.isBlank(sessionKey)) {
            sessionKey = UUID.randomUUID().toString();
        }
        sessionKeyHash = DigestUtils.sha256Hex(sessionKey);
        if (context.getParameter(AuthenticationRequest.AuthenticationRequestConstants.SESSION_KEY) == null) {
            context.addParameter(AuthenticationRequest.AuthenticationRequestConstants.SESSION_KEY, sessionKey);
        }

        String serviceProviderName = context.getServiceProvider().getName();
        SessionContext sessionContext = context.getSessionContext();
        if (sessionContext == null) {
            sessionContext = createSession(context);
        }
        SequenceContext existingSequenceContext = sessionContext.getSequenceContext(serviceProviderName);
        SequenceContext currentSequenceContext = context.getSequenceContext();
        if (existingSequenceContext == null) {
            updateSession(context, sessionContext);
        }
        sessionContext.addSequenceContext(serviceProviderName, currentSequenceContext);
        CacheBackedSessionDAO.getInstance().put(sessionKeyHash, sessionContext);
        return new GatewayHandlerResponse(GatewayHandlerResponse.Status.CONTINUE);
    }
    throw new GatewayRuntimeException("GatewayRequest is not instance of AuthenticationRequest.");
}

From source file:org.wso2.carbon.identity.oauth.endpoint.authz.OAuth2AuthzEndpoint.java

/**
 * Gets the last authenticated value from the commonAuthId cookie
 * @param cookie CommonAuthId cookie//from  w  w  w.  j a  v a  2 s .c  o  m
 * @return the last authenticated timestamp
 */
private long getAuthenticatedTimeFromCommonAuthCookie(Cookie cookie) {
    long authTime = 0;
    if (cookie != null) {
        String sessionContextKey = DigestUtils.sha256Hex(cookie.getValue());
        SessionContext sessionContext = FrameworkUtils.getSessionContextFromCache(sessionContextKey);
        if (sessionContext != null) {
            if (sessionContext.getProperty(FrameworkConstants.UPDATED_TIMESTAMP) != null) {
                authTime = Long
                        .parseLong(sessionContext.getProperty(FrameworkConstants.UPDATED_TIMESTAMP).toString());
            } else {
                authTime = Long
                        .parseLong(sessionContext.getProperty(FrameworkConstants.CREATED_TIMESTAMP).toString());
            }
        }
    }
    return authTime;
}

From source file:org.wso2.carbon.identity.oauth.preprocessor.SHA256TokenPersistencePreprocessor.java

public String getPreprocessedToken(String plainToken) {
    return DigestUtils.sha256Hex(plainToken);
}

From source file:org.wso2.carbon.identity.oauth2.authz.handlers.util.ResponseTypeHandlerUtil.java

private static AccessTokenDO getExistingTokenFromCache(String consumerKey, String scope, String authorizedUser)
        throws IdentityOAuth2Exception {

    AccessTokenDO existingTokenBean = null;
    OAuthCacheKey cacheKey = getOAuthCacheKey(consumerKey, scope, authorizedUser);
    CacheEntry cacheEntry = OAuthCache.getInstance().getValueFromCache(cacheKey);
    if (cacheEntry != null && cacheEntry instanceof AccessTokenDO) {
        existingTokenBean = (AccessTokenDO) cacheEntry;
        if (log.isDebugEnabled()) {
            if (IdentityUtil.isTokenLoggable(IdentityConstants.IdentityTokens.ACCESS_TOKEN)) {
                log.debug("Retrieved active access token(hashed): "
                        + DigestUtils.sha256Hex(existingTokenBean.getAccessToken()) + " in state: "
                        + existingTokenBean.getTokenState() + " for client " + "Id: " + consumerKey + ", user: "
                        + authorizedUser + " and scope: " + scope + " from" + " cache.");

            } else {
                log.debug("Retrieved active access token in state: " + existingTokenBean.getTokenState()
                        + " for " + "" + "client Id: " + consumerKey + ", user: " + authorizedUser
                        + " and scope: " + scope + " from cache.");
            }/*w  w  w  .ja v  a2s . c  o m*/
        }
        if (getAccessTokenExpiryTimeMillis(existingTokenBean) == 0) {
            // Token is expired. Clear it from cache.
            removeTokenFromCache(cacheKey, existingTokenBean);
        }
    }
    return existingTokenBean;
}

From source file:org.wso2.carbon.identity.oauth2.authz.handlers.util.ResponseTypeHandlerUtil.java

private static AccessTokenDO getExistingTokenFromDB(OAuthAuthzReqMessageContext oauthAuthzMsgCtx,
        boolean cacheEnabled) throws IdentityOAuth2Exception {

    OAuth2AuthorizeReqDTO authorizationReqDTO = oauthAuthzMsgCtx.getAuthorizationReqDTO();
    String scope = OAuth2Util.buildScopeString(oauthAuthzMsgCtx.getApprovedScope());
    String consumerKey = authorizationReqDTO.getConsumerKey();
    AuthenticatedUser authorizedUser = authorizationReqDTO.getUser();

    AccessTokenDO existingToken = OAuthTokenPersistenceFactory.getInstance().getAccessTokenDAO()
            .getLatestAccessToken(consumerKey, authorizedUser, getUserStoreDomain(authorizedUser), scope,
                    false);//w  w  w.j a v a2 s  .  c  o  m
    if (existingToken != null) {
        if (log.isDebugEnabled()) {
            if (IdentityUtil.isTokenLoggable(IdentityConstants.IdentityTokens.ACCESS_TOKEN)) {
                log.debug("Retrieved latest access token(hashed): "
                        + DigestUtils.sha256Hex(existingToken.getAccessToken()) + " in state: "
                        + existingToken.getTokenState() + " for client Id: " + consumerKey + " user: "
                        + authorizedUser + " and scope: " + scope + " from db");
            } else {
                log.debug("Retrieved latest access token for client Id: " + consumerKey + " user: "
                        + authorizedUser + " and scope: " + scope + " from db");
            }
        }

        long expireTime = getAccessTokenExpiryTimeMillis(existingToken);
        if (TOKEN_STATE_ACTIVE.equals(existingToken.getTokenState()) && expireTime != 0 && cacheEnabled) {
            // Active token retrieved from db, adding to cache if cacheEnabled
            addTokenToCache(getOAuthCacheKey(consumerKey, scope, authorizedUser.toString()), existingToken);
        }
    }
    return existingToken;
}

From source file:org.wso2.carbon.identity.oauth2.authz.handlers.util.ResponseTypeHandlerUtil.java

private static void storeAccessToken(OAuth2AuthorizeReqDTO authorizationReqDTO, String userStoreDomain,
        AccessTokenDO existingTokenBean, AccessTokenDO newTokenBean) throws IdentityOAuth2Exception {

    try {/*from w w  w . java  2s.c om*/
        OAuthTokenPersistenceFactory.getInstance().getAccessTokenDAO().insertAccessToken(
                newTokenBean.getAccessToken(), authorizationReqDTO.getConsumerKey(), newTokenBean,
                existingTokenBean, userStoreDomain);
    } catch (IdentityException e) {
        String errorMsg;
        if (IdentityUtil.isTokenLoggable(IdentityConstants.IdentityTokens.ACCESS_TOKEN)) {
            errorMsg = "Error occurred while storing new access token(hashed) : "
                    + DigestUtils.sha256Hex(newTokenBean.getAccessToken());

        } else {
            errorMsg = "Error occurred while storing new access token.";
        }
        throw new IdentityOAuth2Exception(errorMsg, e);
    }
}

From source file:org.wso2.carbon.identity.oauth2.authz.handlers.util.ResponseTypeHandlerUtil.java

private static long getAccessTokenExpiryTimeMillis(AccessTokenDO tokenBean) throws IdentityOAuth2Exception {

    // Consider both access and refresh expiry time
    long expireTimeMillis = OAuth2Util.getTokenExpireTimeMillis(tokenBean);

    if (log.isDebugEnabled()) {
        if (IdentityUtil.isTokenLoggable(IdentityConstants.IdentityTokens.ACCESS_TOKEN)) {
            if (expireTimeMillis > 0) {
                log.debug("Access Token(hashed): " + DigestUtils.sha256Hex(tokenBean.getAccessToken()) + " is "
                        + "still valid. Remaining time: " + expireTimeMillis + " ms");
            } else {
                log.debug("Infinite lifetime Access Token(hashed) "
                        + DigestUtils.sha256Hex(tokenBean.getAccessToken()) + " found");
            }//from  ww w .  j  a va2 s. co  m
        } else {
            if (expireTimeMillis > 0) {
                log.debug("Valid access token is found for client: " + tokenBean.getConsumerKey()
                        + ". Remaining " + "time: " + expireTimeMillis + " ms");
            } else {
                log.debug("Infinite lifetime Access Token found for client: " + tokenBean.getConsumerKey());
            }
        }
    }
    return expireTimeMillis;
}

From source file:org.wso2.carbon.identity.oauth2.authz.handlers.util.ResponseTypeHandlerUtil.java

private static boolean isAccessTokenValid(AccessTokenDO tokenBean) throws IdentityOAuth2Exception {

    if (tokenBean != null) {
        long expireTime = getAccessTokenExpiryTimeMillis(tokenBean);
        if (TOKEN_STATE_ACTIVE.equals(tokenBean.getTokenState()) && expireTime != 0) {
            return true;
        } else {/*from   w  w w  . j  av a2s.c  om*/
            if (log.isDebugEnabled()) {
                if (IdentityUtil.isTokenLoggable(IdentityConstants.IdentityTokens.ACCESS_TOKEN)) {
                    log.debug("Access token(hashed): " + DigestUtils.sha256Hex(tokenBean.getAccessToken())
                            + " is" + " not valid anymore");
                } else {
                    log.debug("Latest access token in the database for client: " + tokenBean.getConsumerKey()
                            + "" + " is not valid anymore");
                }
            }
        }
    }
    return false;
}