Example usage for org.apache.commons.io Charsets UTF_8

List of usage examples for org.apache.commons.io Charsets UTF_8

Introduction

In this page you can find the example usage for org.apache.commons.io Charsets UTF_8.

Prototype

Charset UTF_8

To view the source code for org.apache.commons.io Charsets UTF_8.

Click Source Link

Document

Eight-bit Unicode Transformation Format.

Usage

From source file:org.wso2.carbon.identity.openidconnect.DefaultIDTokenBuilder.java

@Override
public String buildIDToken(OAuthAuthzReqMessageContext request, OAuth2AuthorizeRespDTO tokenRespDTO)
        throws IdentityOAuth2Exception {

    String tenantDomain = request.getAuthorizationReqDTO().getTenantDomain();
    IdentityProvider identityProvider = getResidentIdp(tenantDomain);

    FederatedAuthenticatorConfig[] fedAuthnConfigs = identityProvider.getFederatedAuthenticatorConfigs();

    // Get OIDC authenticator
    FederatedAuthenticatorConfig samlAuthenticatorConfig = IdentityApplicationManagementUtil
            .getFederatedAuthenticator(fedAuthnConfigs, IdentityApplicationConstants.Authenticator.OIDC.NAME);
    String issuer = IdentityApplicationManagementUtil
            .getProperty(samlAuthenticatorConfig.getProperties(), OPENID_IDP_ENTITY_ID).getValue();

    long lifetimeInMillis = Integer.parseInt(config.getOpenIDConnectIDTokenExpiration()) * 1000;
    long curTimeInMillis = Calendar.getInstance().getTimeInMillis();
    // setting subject
    String subject = request.getAuthorizationReqDTO().getUser().getAuthenticatedSubjectIdentifier();

    String nonceValue = request.getAuthorizationReqDTO().getNonce();
    LinkedHashSet acrValue = request.getAuthorizationReqDTO().getACRValues();

    String atHash = null;//ww w  .j ava  2s  . co m
    String responseType = request.getAuthorizationReqDTO().getResponseType();
    //at_hash is generated on access token. Hence the check on response type to be id_token token or code
    if (!JWSAlgorithm.NONE.getName().equals(signatureAlgorithm.getName())
            && !OAuthConstants.ID_TOKEN.equalsIgnoreCase(responseType)
            && !OAuthConstants.NONE.equalsIgnoreCase(responseType)) {
        String digAlg = OAuth2Util.mapDigestAlgorithm(signatureAlgorithm);
        MessageDigest md;
        try {
            md = MessageDigest.getInstance(digAlg);
        } catch (NoSuchAlgorithmException e) {
            throw new IdentityOAuth2Exception("Invalid Algorithm : " + digAlg);
        }
        md.update(tokenRespDTO.getAccessToken().getBytes(Charsets.UTF_8));
        byte[] digest = md.digest();
        int leftHalfBytes = 16;
        if (SHA384.equals(digAlg)) {
            leftHalfBytes = 24;
        } else if (SHA512.equals(digAlg)) {
            leftHalfBytes = 32;
        }
        byte[] leftmost = new byte[leftHalfBytes];
        for (int i = 0; i < leftHalfBytes; i++) {
            leftmost[i] = digest[i];
        }
        atHash = new String(Base64.encodeBase64URLSafe(leftmost), Charsets.UTF_8);
    }

    if (log.isDebugEnabled()) {
        StringBuilder stringBuilder = (new StringBuilder()).append("Using issuer ").append(issuer).append("\n")
                .append("Subject ").append(subject).append("\n").append("ID Token life time ")
                .append(lifetimeInMillis / 1000).append("\n").append("Current time ")
                .append(curTimeInMillis / 1000).append("\n").append("Nonce Value ").append(nonceValue)
                .append("\n").append("Signature Algorithm ").append(signatureAlgorithm).append("\n");
        if (log.isDebugEnabled()) {
            log.debug(stringBuilder.toString());
        }
    }

    ArrayList<String> audience = new ArrayList<String>();
    audience.add(request.getAuthorizationReqDTO().getConsumerKey());
    if (CollectionUtils.isNotEmpty(getOIDCEndpointUrl())) {
        audience.addAll(getOIDCEndpointUrl());
    }

    JWTClaimsSet jwtClaimsSet = new JWTClaimsSet();
    jwtClaimsSet.setIssuer(issuer);
    jwtClaimsSet.setAudience(audience);
    jwtClaimsSet.setClaim("azp", request.getAuthorizationReqDTO().getConsumerKey());
    jwtClaimsSet.setExpirationTime(new Date(curTimeInMillis + lifetimeInMillis));
    jwtClaimsSet.setIssueTime(new Date(curTimeInMillis));
    if (request.getAuthorizationReqDTO().getAuthTime() != 0) {
        jwtClaimsSet.setClaim("auth_time", request.getAuthorizationReqDTO().getAuthTime() / 1000);
    }
    if (atHash != null) {
        jwtClaimsSet.setClaim("at_hash", atHash);
    }
    if (nonceValue != null) {
        jwtClaimsSet.setClaim("nonce", nonceValue);
    }
    if (acrValue != null) {
        jwtClaimsSet.setClaim("acr", "urn:mace:incommon:iap:silver");
    }

    request.addProperty(OAuthConstants.ACCESS_TOKEN, tokenRespDTO.getAccessToken());
    request.addProperty(MultitenantConstants.TENANT_DOMAIN, request.getAuthorizationReqDTO().getTenantDomain());
    CustomClaimsCallbackHandler claimsCallBackHandler = OAuthServerConfiguration.getInstance()
            .getOpenIDConnectCustomClaimsCallbackHandler();
    claimsCallBackHandler.handleCustomClaims(jwtClaimsSet, request);
    jwtClaimsSet.setSubject(subject);
    if (JWSAlgorithm.NONE.getName().equals(signatureAlgorithm.getName())) {
        return new PlainJWT(jwtClaimsSet).serialize();
    }

    boolean isJWTSignedWithSPKey = OAuthServerConfiguration.getInstance().isJWTSignedWithSPKey();
    String signingTenantDomain;
    if (isJWTSignedWithSPKey) {
        signingTenantDomain = (String) request.getProperty(MultitenantConstants.TENANT_DOMAIN);
    } else {
        signingTenantDomain = request.getAuthorizationReqDTO().getUser().getTenantDomain();
    }

    return OAuth2Util.signJWT(jwtClaimsSet, signatureAlgorithm, signingTenantDomain).serialize();
}

From source file:org.wso2.carbon.identity.openidconnect.OpenIDConnectSystemClaimImpl.java

/**
 * This returns the base64url encoding of the left-most half of the hash of the octets of the ASCII representation
 * of the param value.//from   w  w w  .  j av  a  2s .c om
 * The hash algorithm used is the hash algorithm used in the alg Header Parameter of the ID Token's JOSE Header.
 * This method generate both c_hash and at_hash values when value is given as authorization code and access token
 * respectively.
 * @param value
 * @return at_hash or c_hash value
 * @throws IdentityOAuth2Exception
 */
private String getHashValue(String value) throws IdentityOAuth2Exception {
    String digAlg = OAuth2Util.mapDigestAlgorithm(signatureAlgorithm);
    MessageDigest md;
    try {
        md = MessageDigest.getInstance(digAlg);
    } catch (NoSuchAlgorithmException e) {
        throw new IdentityOAuth2Exception("Error creating the hash value. Invalid Digest Algorithm: " + digAlg);
    }

    md.update(value.getBytes(Charsets.UTF_8));
    byte[] digest = md.digest();
    int leftHalfBytes = 16;
    if (SHA384.equals(digAlg)) {
        leftHalfBytes = 24;
    } else if (SHA512.equals(digAlg)) {
        leftHalfBytes = 32;
    }
    byte[] leftmost = new byte[leftHalfBytes];
    System.arraycopy(digest, 0, leftmost, 0, leftHalfBytes);
    return new String(Base64.encodeBase64URLSafe(leftmost), Charsets.UTF_8);
}

From source file:org.wso2.carbon.is.migration.service.v550.migrator.OAuthDataMigrator.java

private List<OauthTokenInfo> transformFromOldToNewEncryption(List<OauthTokenInfo> oauthTokenList)
        throws CryptoException {
    List<OauthTokenInfo> updatedOauthTokenList = new ArrayList<>();

    for (OauthTokenInfo oauthTokenInfo : oauthTokenList) {
        if (!CryptoUtil.getDefaultCryptoUtil()
                .base64DecodeAndIsSelfContainedCipherText(oauthTokenInfo.getAccessToken())) {
            byte[] decryptedAccessToken = CryptoUtil.getDefaultCryptoUtil()
                    .base64DecodeAndDecrypt(oauthTokenInfo.getAccessToken(), "RSA");
            String newEncryptedAccesTOken = CryptoUtil.getDefaultCryptoUtil()
                    .encryptAndBase64Encode(decryptedAccessToken);
            byte[] decryptedRefreshToken = CryptoUtil.getDefaultCryptoUtil()
                    .base64DecodeAndDecrypt(oauthTokenInfo.getRefreshToken(), "RSA");
            String newEncryptedRefreshToken = CryptoUtil.getDefaultCryptoUtil()
                    .encryptAndBase64Encode(decryptedRefreshToken);
            TokenPersistenceProcessor tokenPersistenceProcessor = new HashingPersistenceProcessor();
            String accessTokenHash = null;
            String refreshTokenHash = null;
            try {
                accessTokenHash = tokenPersistenceProcessor
                        .getProcessedAccessTokenIdentifier(new String(decryptedAccessToken, Charsets.UTF_8));
                refreshTokenHash = tokenPersistenceProcessor
                        .getProcessedRefreshToken(new String(decryptedRefreshToken, Charsets.UTF_8));
            } catch (IdentityOAuth2Exception e) {
                e.printStackTrace();/*from   w w w.jav a2 s.  c o m*/
            }
            OauthTokenInfo updatedOauthTokenInfo = (new OauthTokenInfo(newEncryptedAccesTOken,
                    newEncryptedRefreshToken, oauthTokenInfo.getTokenId()));
            updatedOauthTokenInfo.setAccessTokenHash(accessTokenHash);
            updatedOauthTokenInfo.setRefreshTokenhash(refreshTokenHash);
            updatedOauthTokenList.add(updatedOauthTokenInfo);
        }
    }

    return updatedOauthTokenList;
}

From source file:org.wso2.carbon.is.migration.service.v550.migrator.OAuthDataMigrator.java

private List<AuthzCodeInfo> transformAuthzCodeFromOldToNewEncryption(List<AuthzCodeInfo> authzCodeInfoList)
        throws CryptoException, IdentityOAuth2Exception {

    List<AuthzCodeInfo> updatedAuthzCodeInfoList = new ArrayList<>();
    for (AuthzCodeInfo authzCodeInfo : authzCodeInfoList) {
        if (!CryptoUtil.getDefaultCryptoUtil()
                .base64DecodeAndIsSelfContainedCipherText(authzCodeInfo.getAuthorizationCode())) {
            byte[] decryptedAuthzCode = CryptoUtil.getDefaultCryptoUtil()
                    .base64DecodeAndDecrypt(authzCodeInfo.getAuthorizationCode(), "RSA");
            String newEncryptedAuthzCode = CryptoUtil.getDefaultCryptoUtil()
                    .encryptAndBase64Encode(decryptedAuthzCode);
            TokenPersistenceProcessor tokenPersistenceProcessor = new HashingPersistenceProcessor();
            String authzCodeHash = null;
            authzCodeHash = tokenPersistenceProcessor
                    .getProcessedAuthzCode(new String(decryptedAuthzCode, Charsets.UTF_8));

            AuthzCodeInfo updatedAuthzCodeInfo = (new AuthzCodeInfo(newEncryptedAuthzCode,
                    authzCodeInfo.getCodeId()));
            updatedAuthzCodeInfo.setAuthorizationCodeHash(authzCodeHash);
            updatedAuthzCodeInfoList.add(updatedAuthzCodeInfo);
        }//from   w  w  w  . j a v  a  2s.  c o  m
    }
    return updatedAuthzCodeInfoList;
}

From source file:org.wso2.carbon.policyeditor.PolicyEditorService.java

/**
 * Retrieves a Policy document from a given URL
 *
 * @param policyURL/*from  ww  w.j av a 2  s .co m*/
 * @return A CDATA Wrapped Policy document if found
 * @throws AxisFault
 */
public String getPolicyDoc(String policyURL) throws AxisFault {
    String policy = "";

    // Open a stream to the policy file using the URL.
    try {
        URL url = new URL(policyURL);

        InputStream in = url.openStream();
        BufferedReader dis = new BufferedReader(new InputStreamReader(in, Charsets.UTF_8));
        StringBuilder fBuf = new StringBuilder();

        String line = "";
        while ((line = dis.readLine()) != null) {
            fBuf.append(line).append("\n");
        }
        in.close();

        policy = fBuf.toString();
        dis.close();
    } catch (IOException e) {
        throw new AxisFault("Axis Error while getting policy docs.", e);
    }

    return "<![CDATA[" + policy + "]]>";
}

From source file:org.wso2.carbon.policyeditor.PolicyEditorService.java

/**
 * Retrieves content from a named schema file bundled as a resource.
 *
 * @param fileName/*from  w w  w.  j  a va  2 s . c  o m*/
 * @return
 * @throws AxisFault
 */
public String getSchema(String fileName) throws AxisFault {
    String schema = "";

    StringBuilder fBuf = null;
    try {
        InputStream in = PolicyEditorService.class
                .getResourceAsStream(ORG_WSO2_CARBON_POLICYEDITOR_XSD + fileName);

        BufferedReader dis = new BufferedReader(new InputStreamReader(in, Charsets.UTF_8));
        fBuf = new StringBuilder();

        String line = "";
        while ((line = dis.readLine()) != null) {
            fBuf.append(line).append("\n");
        }
        in.close();

        schema = fBuf.toString();
        dis.close();
    } catch (IOException e) {
        throw new AxisFault("Axis error while getting schemas.", e);
    }

    return "<![CDATA[" + schema + "]]>";
}

From source file:org.wso2.carbon.policyeditor.PolicyEditorService.java

/**
 * Returns a list of bundled shema (XSD) file names
 *
 * @return A file name list//from  www  .  jav  a2s . co m
 * @throws AxisFault
 */
public String getAvailableSchemas() throws AxisFault {
    String fileList = "";

    StringBuilder fBuf = null;
    try {
        InputStream in = PolicyEditorService.class
                .getResourceAsStream(ORG_WSO2_CARBON_POLICYEDITOR_XSD + "policies.xml");

        BufferedReader dis = new BufferedReader(new InputStreamReader(in, Charsets.UTF_8));
        fBuf = new StringBuilder();

        String line = "";
        while ((line = dis.readLine()) != null) {
            fBuf.append(line).append("\n");
        }
        in.close();

        fileList = fBuf.toString();
        dis.close();
    } catch (IOException e) {
        throw new AxisFault("Axis fault while getting schemas.", e);
    }

    return "<![CDATA[" + fileList + "]]>";
}

From source file:org.wso2.carbon.policyeditor.PolicyEditorService.java

/**
 * Formats a given unformatted XML string
 *
 * @param xml/*from w w  w  .  j a  v  a2s.c o m*/
 * @return A CDATA wrapped, formatted XML String
 */
public String formatXML(String xml) {

    try {
        // create the factory
        DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
        docFactory.setIgnoringComments(true);
        docFactory.setNamespaceAware(true);
        docFactory.setExpandEntityReferences(false);
        SecurityManager securityManager = new SecurityManager();
        securityManager.setEntityExpansionLimit(ENTITY_EXPANSION_LIMIT);
        docFactory.setAttribute(SECURITY_MANAGER_PROPERTY, securityManager);
        DocumentBuilder docBuilder;
        Document xmlDoc;

        // now use the factory to create the document builder
        docFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
        docBuilder = docFactory.newDocumentBuilder();
        docBuilder.setEntityResolver(new CarbonEntityResolver());
        xmlDoc = docBuilder.parse(new ByteArrayInputStream(xml.getBytes(Charsets.UTF_8)));

        OutputFormat format = new OutputFormat(xmlDoc);
        format.setLineWidth(0);
        format.setIndenting(true);
        format.setIndent(2);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        XMLSerializer serializer = new XMLSerializer(baos, format);
        serializer.serialize(xmlDoc);

        xml = baos.toString("UTF-8");

    } catch (ParserConfigurationException pce) {
        throw new IllegalArgumentException("Failed to setup repository: ");
    } catch (Exception e) {
        log.error(e);
    }

    return "<![CDATA[" + xml + "]]>";
}

From source file:org.wso2.carbon.transport.http.netty.util.TestUtil.java

public static String getContent(HttpURLConnection urlConn) throws IOException {
    return new String(ByteStreams.toByteArray(urlConn.getInputStream()), Charsets.UTF_8);
}

From source file:org.wso2.carbon.transport.http.netty.util.TestUtil.java

public static void writeContent(HttpURLConnection urlConn, String content) throws IOException {
    urlConn.getOutputStream().write(content.getBytes(Charsets.UTF_8));
}