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:org.apache.syncope.core.provisioning.api.serialization.AttributeDeserializer.java

@Override
public Attribute deserialize(final JsonParser jp, final DeserializationContext ctx) throws IOException {

    ObjectNode tree = jp.readValueAsTree();

    String name = tree.get("name").asText();

    List<Object> values = new ArrayList<>();
    for (JsonNode node : tree.get("value")) {
        if (node.isNull()) {
            values.add(null);// w w  w  .j  av  a  2s.  c om
        } else if (node.isObject()) {
            values.add(((ObjectNode) node).traverse(jp.getCodec()).readValueAs(GuardedString.class));
        } else if (node.isBoolean()) {
            values.add(node.asBoolean());
        } else if (node.isDouble()) {
            values.add(node.asDouble());
        } else if (node.isLong()) {
            values.add(node.asLong());
        } else if (node.isInt()) {
            values.add(node.asInt());
        } else {
            String text = node.asText();
            if (text.startsWith(AttributeSerializer.BYTE_ARRAY_PREFIX)
                    && text.endsWith(AttributeSerializer.BYTE_ARRAY_SUFFIX)) {

                values.add(Base64.getDecoder().decode(StringUtils.substringBetween(text,
                        AttributeSerializer.BYTE_ARRAY_PREFIX, AttributeSerializer.BYTE_ARRAY_SUFFIX)));
            } else {
                values.add(text);
            }
        }
    }

    return Uid.NAME.equals(name)
            ? new Uid(values.isEmpty() || values.get(0) == null ? null : values.get(0).toString())
            : Name.NAME.equals(name)
                    ? new Name(values.isEmpty() || values.get(0) == null ? null : values.get(0).toString())
                    : AttributeBuilder.build(name, values);
}

From source file:ch.rasc.downloadchart.DownloadChartServlet.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    String dataUrl = request.getParameter("data");
    int contentStartIndex = dataUrl.indexOf(encodingPrefix) + encodingPrefix.length();
    byte[] imageData = Base64.getDecoder().decode(dataUrl.substring(contentStartIndex));

    String format = request.getParameter("format");
    if (format == null) {
        format = "png";
    }//from w w w  .  j av  a  2  s . com

    String filename = request.getParameter("filename");
    if (filename == null) {
        filename = "chart";
    }

    String widthString = request.getParameter("width");
    Integer width = null;
    if (widthString != null) {
        width = Integer.valueOf(widthString);
    }

    String heightString = request.getParameter("height");
    Integer height = null;
    if (heightString != null) {
        height = Integer.valueOf(heightString);
    }

    // String scaleString = request.getParameter("scale");
    // Integer scale = null;
    // if (scaleString != null) {
    // scale = Integer.valueOf(scaleString);
    // }

    if (format.equals("png")) {
        handlePng(response, imageData, width, height, filename);
    } else if (format.equals("jpeg")) {
        JpegOptions options = readOptions(request, "jpeg", JpegOptions.class);
        handleJpg(response, imageData, width, height, filename, options);
    } else if (format.equals("gif")) {
        handleGif(response, imageData, width, height, filename);
    } else if (format.equals("pdf")) {
        PdfOptions options = readOptions(request, "pdf", PdfOptions.class);
        handlePdf(response, imageData, width, height, filename, options);
    }

    response.getOutputStream().flush();
}

From source file:org.codice.ddf.security.handler.api.BSTAuthenticationToken.java

/**
 * Creates an instance of BaseAuthenticationToken by parsing the given credential string. The
 * passed boolean indicates if the provided credentials are encoded or not.
 * If the string contains the necessary components (username, password, realm), a new instance of
 * BaseAuthenticationToken is created and initialized with the credentials. If not, a null value
 * is returned./*from  ww  w.j a v  a2  s  .c om*/
 *
 * @param stringBST unencoded credentials string
 * @return initialized username/password token if parsed successfully, null otherwise
 */
public static BaseAuthenticationToken parse(String stringBST, boolean isEncoded) throws WSSecurityException {
    BaseAuthenticationToken baseAuthenticationToken = null;
    org.apache.xml.security.Init.init();

    String unencodedCreds = isEncoded
            ? new String(Base64.getDecoder().decode(stringBST), StandardCharsets.UTF_8)
            : stringBST;
    if (!StringUtils.isEmpty(unencodedCreds) && unencodedCreds.startsWith(BST_PRINCIPAL)) {
        String[] components = unencodedCreds.split(NEWLINE);
        if (components.length == 3) {
            String p = parseComponent(components[0], BST_PRINCIPAL);
            String c = parseComponent(components[1], BST_CREDENTIALS);
            String r = parseComponent(components[2], BST_REALM);

            baseAuthenticationToken = new BaseAuthenticationToken(p, r, c);
        }
    }

    if (baseAuthenticationToken == null) {
        throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE,
                "Exception decoding specified credentials. Unable to find required components.");
    }

    return baseAuthenticationToken;
}

From source file:org.springframework.cloud.gcp.autoconfigure.sql.SqlCredentialFactory.java

@Override
public Credential create() {
    String credentialResourceLocation = System.getProperty(CREDENTIAL_LOCATION_PROPERTY_NAME);
    String encodedCredential = System.getProperty(CREDENTIAL_ENCODED_KEY_PROPERTY_NAME);

    if (credentialResourceLocation == null && encodedCredential == null) {
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug(CREDENTIAL_LOCATION_PROPERTY_NAME + " and " + CREDENTIAL_ENCODED_KEY_PROPERTY_NAME
                    + " properties do not exist. "
                    + "Socket factory will use application default credentials.");
        }//  w w w. jav  a2 s.c  o m
        return null;
    }

    InputStream credentialsInputStream;

    try {
        if (encodedCredential != null) {
            credentialsInputStream = new ByteArrayInputStream(
                    Base64.getDecoder().decode(encodedCredential.getBytes()));
        } else {
            credentialsInputStream = new FileInputStream(credentialResourceLocation);
        }

        return GoogleCredential.fromStream(credentialsInputStream)
                .createScoped(Collections.singleton(GcpScope.SQLADMIN.getUrl()));
    } catch (IOException ioe) {
        LOGGER.warn("There was an error loading Cloud SQL credential.", ioe);
        return null;
    }

}

From source file:org.hawkular.openshift.auth.BasicAuthentication.java

public void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
        throws IOException, ServletException {

    if (users == null || users.isEmpty()) {
        response.sendError(HttpServletResponse.SC_FORBIDDEN);
        return;/*from  w  ww  . ja  va  2s  .  co  m*/
    }

    String basicHeader = request.getHeader(OpenShiftAuthenticationFilter.AUTHORIZATION_HEADER);
    String username;
    String password;

    if (basicHeader != null && basicHeader.startsWith("Basic ")) {
        basicHeader = basicHeader.substring("Basic ".length());

        String usernamePassword = new String(Base64.getDecoder().decode(basicHeader));
        String[] entries = usernamePassword.split(":", 2);

        if (entries.length == 2) {
            username = entries[0];
            password = entries[1];

            if (username != null && password != null && users.containsKey(username)
                    && isAuthorized(username, password)) {
                filterChain.doFilter(request, response);
                return;
            }
        }
    }
    response.sendError(HttpServletResponse.SC_FORBIDDEN);
}

From source file:org.jaqpot.algorithms.resource.Mopac.java

@POST
@Path("calculate")
public Response calculate(@FormParam("pdbfile") String pdbFile, @HeaderParam("subjectid") String subjectId) {

    try {/*from  w  w w.j a va 2s  .  co m*/
        byte[] file;
        if (pdbFile.startsWith("data:")) {
            String base64pdb = pdbFile.split(",")[1];
            file = Base64.getDecoder().decode(base64pdb.getBytes());
        } else {
            URL pdbURL = new URL(pdbFile);
            file = IOUtils.toByteArray(pdbURL.openStream());
        }
        ResteasyClient client = new ResteasyClientBuilder().disableTrustManager().build();
        ResteasyWebTarget target = client.target("https://apps.ideaconsult.net/enmtest/dataset");
        String fileName = UUID.randomUUID().toString() + ".pdb";
        MultipartFormDataOutput mdo = new MultipartFormDataOutput();
        mdo.addFormData("file", file, MediaType.APPLICATION_OCTET_STREAM_TYPE, fileName);
        GenericEntity<MultipartFormDataOutput> entity = new GenericEntity<MultipartFormDataOutput>(mdo) {
        };

        Response response = target.request().header("subjectid", subjectId).accept(MediaType.APPLICATION_JSON)
                .post(Entity.entity(entity, MediaType.MULTIPART_FORM_DATA_TYPE));

        AmbitTaskArray ambitTaskArray = response.readEntity(AmbitTaskArray.class);

        AmbitTask ambitTask = ambitTaskArray.getTask().get(0);
        String ambitTaskUri = ambitTask.getUri();
        System.out.println("Task POST Dataset:" + ambitTaskUri);
        while (ambitTask.getStatus().equals("Running") || ambitTask.getStatus().equals("Queued")) {
            ambitTaskArray = client.target(ambitTaskUri).request().accept(MediaType.APPLICATION_JSON)
                    .header("subjectid", subjectId).get(AmbitTaskArray.class);
            ambitTask = ambitTaskArray.getTask().get(0);
            try {
                Thread.sleep(500);
            } catch (InterruptedException ex) {
                continue;
            }
        }
        String datasetUri;
        if (ambitTask.getStatus().equals("Completed")) {
            datasetUri = ambitTask.getResult();
        } else {
            return Response.status(Response.Status.BAD_GATEWAY)
                    .entity("Remote error task:" + ambitTask.getUri()).build();
        }

        System.out.println("New Dataset:" + datasetUri);

        MultivaluedMap algorithmFormData = new MultivaluedHashMap();
        algorithmFormData.add("dataset_uri", datasetUri);
        algorithmFormData.add("mopac_commands", "PM3 NOINTER MMOK BONDS MULLIK GNORM=1.0 T=30.00M");

        response = client
                .target("https://apps.ideaconsult.net/enmtest/algorithm/ambit2.mopac.MopacOriginalStructure")
                .request().header("subjectid", subjectId).accept(MediaType.APPLICATION_JSON)
                .post(Entity.form(algorithmFormData));

        ambitTaskArray = response.readEntity(AmbitTaskArray.class);

        ambitTask = ambitTaskArray.getTask().get(0);
        ambitTaskUri = ambitTask.getUri();
        System.out.println("Task POST Dataset:" + ambitTaskUri);
        while (ambitTask.getStatus().equals("Running") || ambitTask.getStatus().equals("Queued")) {
            ambitTaskArray = client.target(ambitTaskUri).request().accept(MediaType.APPLICATION_JSON)
                    .header("subjectid", subjectId).get(AmbitTaskArray.class);
            ambitTask = ambitTaskArray.getTask().get(0);
            try {
                Thread.sleep(500);
            } catch (InterruptedException ex) {
                continue;
            }
        }
        if (ambitTask.getStatus().equals("Completed")) {
            datasetUri = ambitTask.getResult();
        } else {
            return Response.status(Response.Status.BAD_GATEWAY)
                    .entity("Remote error task:" + ambitTask.getUri()).build();
        }

        System.out.println(datasetUri);

        response = client.target(datasetUri).request().header("subjectid", subjectId)
                .accept(MediaType.APPLICATION_JSON).get();

        Dataset dataset = response.readEntity(Dataset.class);

        return Response.ok(dataset.getDataEntry().get(0).getValues()).build();
    } catch (MalformedURLException ex) {
        return Response.status(Response.Status.BAD_REQUEST)
                .entity("Bad pdb file:" + pdbFile + " " + ex.getMessage()).build();
    } catch (IOException ex) {
        return Response.status(Response.Status.BAD_GATEWAY).entity(ex.getMessage()).build();
    }
}

From source file:org.jaqpot.algorithm.resource.Mopac.java

@POST
@Path("calculate")
public Response calculate(@FormParam("pdbfile") String pdbFile, @HeaderParam("subjectid") String subjectId) {

    try {/*from  www  .  j  a  va  2  s  . c  o m*/
        byte[] file;
        if (pdbFile.startsWith("data:")) {
            String base64pdb = pdbFile.split(",")[1];
            file = Base64.getDecoder().decode(base64pdb.getBytes());
        } else {
            URL pdbURL = new URL(pdbFile);
            file = IOUtils.toByteArray(pdbURL.openStream());
        }
        ResteasyClient client = new ResteasyClientBuilder().disableTrustManager().build();
        ResteasyWebTarget target = client.target("https://apps.ideaconsult.net/enmtest/dataset");
        String fileName = UUID.randomUUID().toString() + ".pdb";
        MultipartFormDataOutput mdo = new MultipartFormDataOutput();
        mdo.addFormData("file", file, MediaType.APPLICATION_OCTET_STREAM_TYPE, fileName);
        GenericEntity<MultipartFormDataOutput> entity = new GenericEntity<MultipartFormDataOutput>(mdo) {
        };

        Response response = target.request().header("subjectid", subjectId).accept(MediaType.APPLICATION_JSON)
                .post(Entity.entity(entity, MediaType.MULTIPART_FORM_DATA_TYPE));

        AmbitTaskArray ambitTaskArray = response.readEntity(AmbitTaskArray.class);

        AmbitTask ambitTask = ambitTaskArray.getTask().get(0);
        String ambitTaskUri = ambitTask.getUri();
        System.out.println("Task POST Dataset:" + ambitTaskUri);
        while (ambitTask.getStatus().equals("Running") || ambitTask.getStatus().equals("Queued")) {
            ambitTaskArray = client.target(ambitTaskUri).request().accept(MediaType.APPLICATION_JSON)
                    .header("subjectid", subjectId).get(AmbitTaskArray.class);
            ambitTask = ambitTaskArray.getTask().get(0);
            try {
                Thread.sleep(500);
            } catch (InterruptedException ex) {
                continue;
            }
        }
        String datasetUri;
        if (ambitTask.getStatus().equals("Completed")) {
            datasetUri = ambitTask.getResult();
        } else {
            return Response.status(Response.Status.BAD_GATEWAY).entity(ErrorReportFactory
                    .remoteError(ambitTaskUri, ErrorReportFactory.internalServerError(), null)).build();
        }

        System.out.println("New Dataset:" + datasetUri);

        MultivaluedMap algorithmFormData = new MultivaluedHashMap();
        algorithmFormData.add("dataset_uri", datasetUri);
        algorithmFormData.add("mopac_commands", "PM3 NOINTER MMOK BONDS MULLIK GNORM=1.0 T=30.00M");

        response = client
                .target("https://apps.ideaconsult.net/enmtest/algorithm/ambit2.mopac.MopacOriginalStructure")
                .request().header("subjectid", subjectId).accept(MediaType.APPLICATION_JSON)
                .post(Entity.form(algorithmFormData));

        ambitTaskArray = response.readEntity(AmbitTaskArray.class);

        ambitTask = ambitTaskArray.getTask().get(0);
        ambitTaskUri = ambitTask.getUri();
        System.out.println("Task POST Dataset:" + ambitTaskUri);
        while (ambitTask.getStatus().equals("Running") || ambitTask.getStatus().equals("Queued")) {
            ambitTaskArray = client.target(ambitTaskUri).request().accept(MediaType.APPLICATION_JSON)
                    .header("subjectid", subjectId).get(AmbitTaskArray.class);
            ambitTask = ambitTaskArray.getTask().get(0);
            try {
                Thread.sleep(500);
            } catch (InterruptedException ex) {
                continue;
            }
        }
        if (ambitTask.getStatus().equals("Completed")) {
            datasetUri = ambitTask.getResult();
        } else {
            return Response.status(Response.Status.BAD_GATEWAY).entity(ErrorReportFactory
                    .remoteError(ambitTaskUri, ErrorReportFactory.internalServerError(), null)).build();
        }

        System.out.println(datasetUri);

        response = client.target(datasetUri).request().header("subjectid", subjectId)
                .accept(MediaType.APPLICATION_JSON).get();

        Dataset dataset = response.readEntity(Dataset.class);

        return Response.ok(dataset.getDataEntry().get(0).getValues()).build();
    } catch (MalformedURLException ex) {
        return Response.status(Response.Status.BAD_REQUEST)
                .entity(ErrorReportFactory.badRequest(ex.getMessage(), "Bad pdb file:" + pdbFile)).build();
    } catch (IOException ex) {
        return Response.status(Response.Status.BAD_GATEWAY).entity(
                ErrorReportFactory.remoteError(ex.getMessage(), ErrorReportFactory.internalServerError(), ex))
                .build();
    }
}

From source file:jease.site.Authorizations.java

private static String decodeBasicAuthorization(String authorizationHeader) {
    if (authorizationHeader == null) {
        return null;
    }/*from w  w  w  .j a  v  a2s  . c  o  m*/
    String userpassEncoded = authorizationHeader.substring(6);
    return new String(Base64.getDecoder().decode(userpassEncoded));
}

From source file:ai.susi.tools.JsonSignature.java

/**
 * Verfies if the signature of a JSONObject is valid
 * @param obj the JSONObject/*from  www  .j av  a  2  s  .  c om*/
 * @param key the public key of the signature issuer
 * @return true if the signature is valid
 * @throws SignatureException if the JSONObject does not have a signature or something with the JSONObject is bogus
 * @throws InvalidKeyException if the key is not valid (for example not RSA)
 */
public static boolean verify(JSONObject obj, PublicKey key) throws SignatureException, InvalidKeyException {

    if (!obj.has(signatureString))
        throw new SignatureException("No signature supplied");

    Signature signature;
    try {
        signature = Signature.getInstance("SHA256withRSA");
    } catch (NoSuchAlgorithmException e) {
        return false; //does not happen
    }

    String sigString = obj.getString(signatureString);
    byte[] sig = Base64.getDecoder().decode(sigString);
    obj.remove(signatureString);

    signature.initVerify(key);
    signature.update(obj.toString().getBytes(StandardCharsets.UTF_8));
    boolean res = signature.verify(sig);

    obj.put(signatureString, sigString);

    return res;
}

From source file:com.formkiq.core.service.crypto.SecureTokenServiceImpl.java

@Override
public String decryptToken(final PublicKey publicKey, final String encryptedToken)
        throws GeneralSecurityException {

    Cipher cipher = Cipher.getInstance("RSA");

    cipher.init(Cipher.DECRYPT_MODE, publicKey);

    byte[] bs = cipher.doFinal(Base64.getDecoder().decode(encryptedToken));
    return Strings.toString(bs);
}