Example usage for java.util Base64 getDecoder

List of usage examples for java.util Base64 getDecoder

Introduction

In this page you can find the example usage for java.util Base64 getDecoder.

Prototype

public static Decoder getDecoder() 

Source Link

Document

Returns a Decoder that decodes using the Basic type base64 encoding scheme.

Usage

From source file:gov.nist.healthcare.ttt.parsing.Parsing.java

private static String getDocumentFromSoap(String soap) {
    Envelope env = (Envelope) JAXB.unmarshal(new StringReader(soap), Envelope.class);

    Body body = env.getBody();/*w  w  w.  ja v a 2 s . c o  m*/
    List<Object> any = body.getAny();
    Element regresp = (Element) any.get(0);

    ProvideAndRegisterDocumentSetRequestType pnr = (ProvideAndRegisterDocumentSetRequestType) JAXB.unmarshal(
            new StringReader(MiscUtil.xmlToString(regresp)), ProvideAndRegisterDocumentSetRequestType.class);
    List<Document> documents = pnr.getDocument();
    if (!documents.isEmpty()) {
        Document document = documents.get(0);
        byte[] documentByteArray = document.getValue();

        String payload = new String(documentByteArray);
        if (Parsing.isBase64Encoded(payload)) {
            return new String(Base64.getDecoder().decode(documentByteArray));
        } else {
            return payload;
        }
    }
    return null;
}

From source file:de.thingweb.client.security.Security4NicePlugfest.java

public String requestASToken(Registration registration, String[] adds) throws IOException {
    String asToken = null;/*from ww w . j  a  v a  2s .  co m*/

    // Token Acquisition
    // Create a HTTP request as in the following prototype and send
    // it via TLS to the AM
    //
    // Token Acquisition
    // Create a HTTP request as in the following prototype and send
    // it via TLS to the AM
    // Request
    // POST /iam-services/0.1/oidc/am/token HTTP/1.1
    URL urlTokenAcquisition = new URL(HTTPS_PREFIX + HOST + REQUEST_TOKEN_AQUISITION);

    HttpsURLConnection httpConTokenAcquisition = (HttpsURLConnection) urlTokenAcquisition.openConnection();
    httpConTokenAcquisition.setDoOutput(true);
    httpConTokenAcquisition.setRequestProperty("Host", REQUEST_HEADER_HOST);
    httpConTokenAcquisition.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    httpConTokenAcquisition.setRequestProperty("Accept", "application/json");
    // httpConTokenAcquisition.setRequestProperty("Authorization",
    // "Basic Base64(<c_id>:<c_secret>");
    String auth = registration.c_id + ":" + registration.c_secret;
    String authb = "Basic " + new String(Base64.getEncoder().encode(auth.getBytes()));
    httpConTokenAcquisition.setRequestProperty("Authorization", authb);
    httpConTokenAcquisition.setRequestMethod("POST");

    String requestBodyTokenAcquisition = "grant_type=client_credentials";
    if (adds == null || adds.length == 0) {
        // no additions
    } else {
        if (adds.length % 2 == 0) {
            for (int i = 0; i < (adds.length - 1); i += 2) {
                requestBodyTokenAcquisition += "&";
                requestBodyTokenAcquisition += URLEncoder.encode(adds[i], "UTF-8");
                requestBodyTokenAcquisition += "=";
                requestBodyTokenAcquisition += URLEncoder.encode(adds[i + 1], "UTF-8");
            }
        } else {
            log.warn(
                    "Additional information for token not used! Not a multiple of 2: " + Arrays.toString(adds));
        }
    }

    OutputStream outTokenAcquisition = httpConTokenAcquisition.getOutputStream();
    outTokenAcquisition.write(requestBodyTokenAcquisition.getBytes());
    outTokenAcquisition.close();

    int responseCodeoutTokenAcquisition = httpConTokenAcquisition.getResponseCode();
    log.info("responseCode TokenAcquisition for " + urlTokenAcquisition + ": "
            + responseCodeoutTokenAcquisition);

    if (responseCodeoutTokenAcquisition == 200) {
        // everything ok
        InputStream isTA = httpConTokenAcquisition.getInputStream();
        byte[] bisTA = getBytesFromInputStream(isTA);
        String jsonResponseTA = new String(bisTA);
        log.info(jsonResponseTA);

        ObjectMapper mapper = new ObjectMapper();
        JsonFactory factory = mapper.getFactory();
        JsonParser jp = factory.createParser(bisTA);
        JsonNode actualObj = mapper.readTree(jp);

        JsonNode access_token = actualObj.get("access_token");
        if (access_token == null || access_token.getNodeType() != JsonNodeType.STRING) {
            log.error("access_token: " + access_token);
        } else {
            // ok so far
            // access_token provides a JWT structure
            // see Understanding JWT
            // https://developer.atlassian.com/static/connect/docs/latest/concepts/understanding-jwt.html

            log.info("access_token: " + access_token);
            // http://jwt.io/

            // TODO verify signature (e.g., use Jose4J)

            // Note: currently we assume signature is fine.. we just fetch
            // "as_token"
            String[] decAT = access_token.textValue().split("\\.");
            if (decAT == null || decAT.length != 3) {
                log.error("Cannot build JWT tripple structure for " + access_token);
            } else {
                assert (decAT.length == 3);
                // JWT structure
                // decAT[0]; // header
                // decAT[1]; // payload
                // decAT[2]; // signature
                String decAT1 = new String(Base64.getDecoder().decode(decAT[1]));
                JsonParser jpas = factory.createParser(decAT1);
                JsonNode payload = mapper.readTree(jpas);
                JsonNode as_token = payload.get("as_token");
                if (as_token == null || as_token.getNodeType() != JsonNodeType.STRING) {
                    log.error("as_token: " + as_token);
                } else {
                    log.info("as_token: " + as_token);
                    asToken = as_token.textValue();
                }
            }
        }

    } else {
        // error
        InputStream error = httpConTokenAcquisition.getErrorStream();
        byte[] berror = getBytesFromInputStream(error);
        log.error(new String(berror));
    }

    httpConTokenAcquisition.disconnect();

    return asToken;
}

From source file:org.wso2.carbon.siddhi.editor.core.internal.ServiceComponent.java

@POST
@Path("/workspace/write")
@Produces("application/json")
public Response write(String payload) {
    try {/*from www  .j a v  a  2s .c  om*/
        String location = (Paths.get(Constants.RUNTIME_PATH, Constants.DIRECTORY_DEPLOYMENT,
                Constants.DIRECTORY_WORKSPACE)).toString();
        String configName = "";
        String config = "";
        Matcher configNameMatcher = Pattern.compile("configName=(.*?)&").matcher(payload);
        while (configNameMatcher.find()) {
            configName = configNameMatcher.group(1);
        }
        String[] splitConfigContent = payload.split("config=");
        if (splitConfigContent.length > 1) {
            config = splitConfigContent[1];
        }
        byte[] base64Config = Base64.getDecoder().decode(config);
        byte[] base64ConfigName = Base64.getDecoder().decode(configName);
        StringBuilder pathBuilder = new StringBuilder();
        pathBuilder.append(location).append(System.getProperty(FILE_SEPARATOR))
                .append(new String(base64ConfigName));
        Files.write(Paths.get(pathBuilder.toString()), base64Config);
        JsonObject entity = new JsonObject();
        entity.addProperty(STATUS, SUCCESS);
        entity.addProperty("path", location);
        return Response.status(Response.Status.OK).entity(entity).type(MediaType.APPLICATION_JSON).build();
    } catch (IOException e) {
        return Response.serverError().entity("failed." + e.getMessage()).build();
    } catch (Throwable ignored) {
        return Response.serverError().entity("failed").build();
    }
}

From source file:org.siphon.jsmongo.MongoExecutor.java

private byte[] parseBinary(Object value) throws SqlExecutorException {
    if (value instanceof byte[]) {
        return (byte[]) value;
    } else if (value instanceof Byte[]) {
        return ArrayUtils.toPrimitive((Byte[]) value);
    }//from  w  w  w .  j a  va2 s . co  m
    if (value instanceof ScriptObjectMirror && ((ScriptObjectMirror) value).isArray()) {
        value = ((ScriptObjectMirror) value).to(NativeArray.class);
    }
    if (value instanceof NativeArray) {
        NativeArray arr = (NativeArray) value;
        byte[] r = new byte[JsTypeUtil.getArrayLength(arr)];
        for (int i = 0; i < JsTypeUtil.getArrayLength(arr); i++) {
            if (arr.get(i) instanceof Byte) {
                r[i] = (Byte) arr.get(i);
            } else if (arr.get(i) instanceof Double) {
                r[i] = ((Double) arr.get(i)).byteValue();
            } else if (arr.get(i) instanceof Integer) {
                r[i] = ((Integer) arr.get(i)).byteValue();
            }
        }
        return r;
    } else if (value instanceof String) {
        Decoder decoder = Base64.getDecoder();
        try {
            return decoder.decode((String) value);
        } catch (Exception e) {
            throw new SqlExecutorException("cannot parse base64 binary data " + value, e);
        }
    } else {
        throw new SqlExecutorException("unkown binary data " + value + " " + value.getClass());
    }
}

From source file:org.wso2.carbon.siddhi.editor.core.internal.EditorMicroservice.java

@POST
@Path("/workspace/write")
@Produces("application/json")
public Response write(String payload) {
    try {/*from   ww  w  . j ava2 s.  c  om*/
        String location = (Paths.get(Constants.RUNTIME_PATH, Constants.DIRECTORY_DEPLOYMENT)).toString();
        String configName = "";
        String config = "";
        Matcher configNameMatcher = Pattern.compile("configName=(.*?)&").matcher(payload);
        while (configNameMatcher.find()) {
            configName = configNameMatcher.group(1);
        }
        String[] splitConfigContent = payload.split("config=");
        if (splitConfigContent.length > 1) {
            config = splitConfigContent[1];
        }
        byte[] base64Config = Base64.getDecoder().decode(config);
        byte[] base64ConfigName = Base64.getDecoder().decode(configName);
        java.nio.file.Path filePath = SecurityUtil.resolvePath(Paths.get(location).toAbsolutePath(),
                Paths.get(new String(base64ConfigName, Charset.defaultCharset())));
        Files.write(filePath, base64Config);
        java.nio.file.Path fileNamePath = filePath.getFileName();
        if (null != fileNamePath) {
            String siddhiAppName = fileNamePath.toString().replace(Constants.SIDDHI_APP_FILE_EXTENSION, "");
            if (null != EditorDataHolder.getDebugProcessorService().getSiddhiAppRuntimeHolder(siddhiAppName)) {
                //making the app faulty until the file gets deployed again for editor usage purposes
                EditorDataHolder.getDebugProcessorService().getSiddhiAppRuntimeHolder(siddhiAppName)
                        .setMode(DebugRuntime.Mode.FAULTY);
            }
        }
        JsonObject entity = new JsonObject();
        entity.addProperty(STATUS, SUCCESS);
        entity.addProperty("path", Constants.DIRECTORY_WORKSPACE);
        return Response.status(Response.Status.OK).entity(entity).type(MediaType.APPLICATION_JSON).build();
    } catch (IOException e) {
        return Response.serverError().entity("failed." + e.getMessage()).build();
    } catch (Throwable ignored) {
        return Response.serverError().entity("failed").build();
    }
}

From source file:org.hyperledger.fabric.sdk.Endpoint.java

byte[] getClientTLSCertificateDigest() {
    //The digest must be SHA256 over the DER encoded certificate. The PEM has the exact DER sequence in hex encoding around the begin and end markers

    if (tlsClientCertificatePEMBytes != null && clientTLSCertificateDigest == null) {

        String pemCert = new String(tlsClientCertificatePEMBytes, UTF_8);
        byte[] derBytes = Base64.getDecoder().decode(pemCert
                .replaceAll("-+[ \t]*(BEGIN|END)[ \t]+CERTIFICATE[ \t]*-+", "").replaceAll("\\s", "").trim());

        Digest digest = new SHA256Digest();
        clientTLSCertificateDigest = new byte[digest.getDigestSize()];
        digest.update(derBytes, 0, derBytes.length);
        digest.doFinal(clientTLSCertificateDigest, 0);
    }//from   w  w  w . java2s.c om

    return clientTLSCertificateDigest;
}

From source file:org.onehippo.forge.content.exim.repository.jaxrs.AbstractContentEximService.java

/**
 * Find user principal's name from {@code securityContext} or {@code request}.
 * @param securityContext security context
 * @param request servlet request/*from   w w  w .  ja v  a2 s. c  om*/
 * @return user principal's name from {@code securityContext} or {@code request}
 */
protected String getUserPrincipalName(SecurityContext securityContext, HttpServletRequest request) {
    if (securityContext != null) {
        Principal userPrincipal = securityContext.getUserPrincipal();
        if (userPrincipal != null) {
            return userPrincipal.getName();
        }
    }

    if (request != null) {
        Principal userPrincipal = request.getUserPrincipal();
        if (userPrincipal != null) {
            return userPrincipal.getName();
        }

        final String authHeader = request.getHeader("Authorization");

        if (StringUtils.isNotBlank(authHeader)) {
            if (StringUtils.startsWithIgnoreCase(authHeader, "Basic ")) {
                final String encoded = authHeader.substring(6).trim();
                final String decoded = new String(Base64.getDecoder().decode(encoded));
                return StringUtils.substringBefore(decoded, ":");
            }
        }
    }

    return null;
}

From source file:org.javabeanstack.util.Strings.java

/**
 * Decodifica una cadena base 64 a base 10 
 * @param messageEncode cadena//from  w  ww .j  ava  2s  .co  m
 * @return cadena decodificada.
 */
public static String decode64(String messageEncode) {
    if (messageEncode == null) {
        return null;
    }
    Base64.Decoder decoder = Base64.getDecoder();
    byte[] decodedContent = decoder.decode(messageEncode);
    return new String(decodedContent);
}

From source file:org.wso2.carbon.apimgt.rest.api.authenticator.AuthenticatorService.java

private String getUsernameFromJWT(String jwt) throws KeyManagementException {
    if (jwt != null && jwt.contains(".")) {
        String[] jwtParts = jwt.split("\\.");
        JWTTokenPayload jwtHeader = new Gson().fromJson(
                new String(Base64.getDecoder().decode(jwtParts[1]), StandardCharsets.UTF_8),
                JWTTokenPayload.class);

        // Removing "@carbon.super" part explicitly (until IS side is fixed to drop it)
        String username = jwtHeader.getSub();
        username = username.replace("@carbon.super", "");
        return username;
    } else {/*www .  ja  va2 s.com*/
        log.error("JWT Parsing failed. Invalid JWT: " + jwt);
        throw new KeyManagementException("JWT Parsing failed. Invalid JWT.");
    }
}

From source file:org.wso2.carbon.siddhi.editor.core.internal.ServiceComponent.java

@POST
@Path("/workspace/export")
@Produces("application/json")
public Response export(String payload) {
    try {/*from   ww  w.  ja  v a  2 s  .c  o  m*/
        String location = "";
        String configName = "";
        String config = "";
        Matcher locationMatcher = Pattern.compile("location=(.*?)&configName").matcher(payload);
        while (locationMatcher.find()) {
            location = locationMatcher.group(1);
        }
        Matcher configNameMatcher = Pattern.compile("configName=(.*?)&").matcher(payload);
        while (configNameMatcher.find()) {
            configName = configNameMatcher.group(1);
        }
        String[] splitConfigContent = payload.split("config=");
        if (splitConfigContent.length > 1) {
            config = splitConfigContent[1];
        }
        byte[] base64Config = Base64.getDecoder().decode(config);
        byte[] base64ConfigName = Base64.getDecoder().decode(configName);
        byte[] base64Location = Base64.getDecoder().decode(location);
        Files.write(Paths.get(
                new String(base64Location) + System.getProperty(FILE_SEPARATOR) + new String(base64ConfigName)),
                base64Config);
        JsonObject entity = new JsonObject();
        entity.addProperty(STATUS, SUCCESS);
        return Response.status(Response.Status.OK).entity(entity).type(MediaType.APPLICATION_JSON).build();
    } catch (IOException e) {
        return Response.serverError().entity("failed." + e.getMessage()).build();
    } catch (Throwable ignored) {
        return Response.serverError().entity("failed").build();
    }
}