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.flowable.ui.modeler.service.FlowableDecisionTableService.java

public DecisionTableRepresentation saveDecisionTable(String decisionTableId,
        DecisionTableSaveRepresentation saveRepresentation) {

    User user = SecurityUtils.getCurrentUserObject();
    Model model = getModel(decisionTableId, false, false);

    String decisionKey = saveRepresentation.getDecisionTableRepresentation().getKey();
    ModelKeyRepresentation modelKeyInfo = modelService.validateModelKey(model, model.getModelType(),
            decisionKey);//from  w w  w. j  a v a2s .com
    if (modelKeyInfo.isKeyAlreadyExists()) {
        throw new BadRequestException("Provided model key already exists: " + decisionKey);
    }

    model.setName(saveRepresentation.getDecisionTableRepresentation().getName());
    model.setKey(decisionKey);
    model.setDescription(saveRepresentation.getDecisionTableRepresentation().getDescription());

    saveRepresentation.getDecisionTableRepresentation().getDecisionTableDefinition().setKey(decisionKey);

    String editorJson = null;
    try {
        editorJson = objectMapper.writeValueAsString(
                saveRepresentation.getDecisionTableRepresentation().getDecisionTableDefinition());
    } catch (Exception e) {
        LOGGER.error("Error while processing decision table json", e);
        throw new InternalServerErrorException("Decision table could not be saved " + decisionTableId);
    }

    String filteredImageString = saveRepresentation.getDecisionTableImageBase64()
            .replace("data:image/png;base64,", "");
    byte[] imageBytes = Base64.getDecoder().decode(filteredImageString);
    model = modelService.saveModel(model, editorJson, imageBytes, saveRepresentation.isNewVersion(),
            saveRepresentation.getComment(), user);
    DecisionTableRepresentation result = new DecisionTableRepresentation(model);
    result.setDecisionTableDefinition(
            saveRepresentation.getDecisionTableRepresentation().getDecisionTableDefinition());
    return result;
}

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

@GET
@Path("/workspace/listFiles/samples")
@Produces("application/json")
public Response filesInSamplePath(@QueryParam("path") String relativePath) {
    try {/*ww w . ja  v a2  s .  c o  m*/
        String location = (Paths.get(Constants.CARBON_HOME, Constants.DIRECTORY_SAMPLE,
                Constants.DIRECTORY_ARTIFACTS)).toString();
        java.nio.file.Path pathLocation = SecurityUtil.resolvePath(Paths.get(location).toAbsolutePath(),
                Paths.get(new String(Base64.getDecoder().decode(relativePath), Charset.defaultCharset())));
        return Response.status(Response.Status.OK).entity(workspace.listFilesInPath(pathLocation))
                .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.openhab.binding.loxone.internal.core.LxWsSecurityToken.java

private Cipher getRsaCipher(String key) {
    try {/*from ww w  .jav  a 2  s  .c  o m*/
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        String keyString = key.replace("-----BEGIN CERTIFICATE-----", "").replace("-----END CERTIFICATE-----",
                "");
        byte[] keyData = Base64.getDecoder().decode(keyString);
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyData);
        PublicKey publicKey = keyFactory.generatePublic(keySpec);
        logger.debug("[{}] Miniserver public key: {}", debugId, publicKey);
        Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
        cipher.init(Cipher.PUBLIC_KEY, publicKey);
        logger.debug("[{}] Initialized RSA public key cipher", debugId);
        return cipher;
    } catch (InvalidKeyException | NoSuchAlgorithmException | NoSuchPaddingException
            | InvalidKeySpecException e) {
        setError(LxOfflineReason.INTERNAL_ERROR, "Exception enabling RSA cipher: " + e.getMessage());
        return null;
    }
}

From source file:bioLockJ.module.agent.MailAgent.java

private static byte[] base64Decode(final String encodedPassword) throws IOException {
    return Base64.getDecoder().decode(encodedPassword);
}

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

@GET
@Path("/workspace/listFiles")
@Produces("application/json")
public Response filesInPath(@QueryParam("path") String path) {
    try {//from w w  w  .  j  a  v  a 2  s  .c o  m
        return Response.status(Response.Status.OK)
                .entity(workspace.listFilesInPath(new String(Base64.getDecoder().decode(path))))
                .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.codice.ddf.cxf.paos.PaosInInterceptor.java

private String createToken(String authorization) throws IOException {
    String token = null;//from   ww  w .ja  v  a2 s. com
    if (authorization != null) {
        if (StringUtils.startsWithIgnoreCase(authorization, BASIC)) {
            byte[] decode = Base64.getDecoder().decode(authorization.split("\\s")[1]);
            if (decode != null) {
                String userPass = new String(decode, StandardCharsets.UTF_8);
                String[] authComponents = userPass.split(":");
                if (authComponents.length == 2) {
                    token = getUsernameToken(authComponents[0], authComponents[1]);
                } else if ((authComponents.length == 1) && (userPass.endsWith(":"))) {
                    token = getUsernameToken(authComponents[0], "");
                }
            }
        } else if (StringUtils.startsWithIgnoreCase(authorization, SAML)) {
            token = RestSecurity.inflateBase64(authorization.split("\\s")[1]);
        }
    }
    return token;
}

From source file:com.amazonaws.serverless.proxy.internal.servlet.AwsProxyHttpServletRequest.java

@Override
public ServletInputStream getInputStream() throws IOException {
    byte[] bodyBytes = request.getBody().getBytes();
    if (request.isBase64Encoded()) {
        bodyBytes = Base64.getDecoder().decode(request.getBody());
    }//from  w w  w .  java2 s  . co m
    ByteArrayInputStream requestBodyStream = new ByteArrayInputStream(bodyBytes);
    return new ServletInputStream() {

        private ReadListener listener;

        @Override
        public boolean isFinished() {
            return true;
        }

        @Override
        public boolean isReady() {
            return true;
        }

        @Override
        public void setReadListener(ReadListener readListener) {
            listener = readListener;
            try {
                listener.onDataAvailable();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        @Override
        public int read() throws IOException {
            int readByte = requestBodyStream.read();
            if (requestBodyStream.available() == 0 && listener != null) {
                listener.onAllDataRead();
            }
            return readByte;
        }
    };
}

From source file:org.siphon.common.js.JsTypeUtil.java

private static byte[] parseBinary(Object value) throws UnsupportedConversionException {
    if (value instanceof byte[]) {
        return (byte[]) value;
    } else if (value instanceof Byte[]) {
        return ArrayUtils.toPrimitive((Byte[]) value);
    }/*from   ww w  . j  av  a  2  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 UnsupportedConversionException("cannot parse base64 binary data " + value, e);
        }
    } else {
        throw new UnsupportedConversionException("unkown binary data " + value + " " + value.getClass(), null);
    }
}

From source file:org.codice.ddf.security.certificate.keystore.editor.KeystoreEditor.java

private synchronized void addToStore(String alias, String keyPassword, String storePassword, String data,
        String type, String fileName, String path, String storepass, KeyStore store)
        throws KeystoreEditorException {
    OutputStream fos = null;//from  w  w  w  . j av a2s .c o  m
    try (InputStream inputStream = new ByteArrayInputStream(Base64.getDecoder().decode(data))) {
        if (StringUtils.isBlank(alias)) {
            throw new IllegalArgumentException("Alias cannot be null.");
        }
        Path storeFile = Paths.get(path);
        //check the two most common key/cert stores first (pkcs12 and jks)
        if (PKCS12_TYPE.equals(type) || StringUtils.endsWithIgnoreCase(fileName, ".p12")) {
            //priv key + cert chain
            KeyStore pkcs12Store = KeyStore.getInstance("PKCS12");
            pkcs12Store.load(inputStream, storePassword.toCharArray());
            Certificate[] chain = pkcs12Store.getCertificateChain(alias);
            Key key = pkcs12Store.getKey(alias, keyPassword.toCharArray());
            if (key != null) {
                store.setKeyEntry(alias, key, keyPassword.toCharArray(), chain);
                fos = Files.newOutputStream(storeFile);
                store.store(fos, storepass.toCharArray());
            }
        } else if (JKS_TYPE.equals(type) || StringUtils.endsWithIgnoreCase(fileName, ".jks")) {
            //java keystore file
            KeyStore jks = KeyStore.getInstance("jks");
            jks.load(inputStream, storePassword.toCharArray());
            Enumeration<String> aliases = jks.aliases();

            //we are going to store all entries from the jks regardless of the passed in alias
            while (aliases.hasMoreElements()) {
                String jksAlias = aliases.nextElement();

                if (jks.isKeyEntry(jksAlias)) {
                    Key key = jks.getKey(jksAlias, keyPassword.toCharArray());
                    Certificate[] certificateChain = jks.getCertificateChain(jksAlias);
                    store.setKeyEntry(jksAlias, key, keyPassword.toCharArray(), certificateChain);
                } else {
                    Certificate certificate = jks.getCertificate(jksAlias);
                    store.setCertificateEntry(jksAlias, certificate);
                }
            }

            fos = Files.newOutputStream(storeFile);
            store.store(fos, storepass.toCharArray());
            //need to parse der separately from pem, der has the same mime type but is binary hence checking both
        } else if (DER_TYPE.equals(type) && StringUtils.endsWithIgnoreCase(fileName, ".der")) {
            ASN1InputStream asn1InputStream = new ASN1InputStream(inputStream);
            ASN1Primitive asn1Primitive = asn1InputStream.readObject();
            X509CertificateHolder x509CertificateHolder = new X509CertificateHolder(asn1Primitive.getEncoded());
            CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509", "BC");
            Certificate certificate = certificateFactory
                    .generateCertificate(new ByteArrayInputStream(x509CertificateHolder.getEncoded()));
            X500Name x500name = new JcaX509CertificateHolder((X509Certificate) certificate).getSubject();
            RDN cn = x500name.getRDNs(BCStyle.CN)[0];
            String cnStr = IETFUtils.valueToString(cn.getFirst().getValue());
            if (!store.isCertificateEntry(cnStr) && !store.isKeyEntry(cnStr)) {
                store.setCertificateEntry(cnStr, certificate);
            }
            store.setCertificateEntry(alias, certificate);
            fos = Files.newOutputStream(storeFile);
            store.store(fos, storepass.toCharArray());
            //if it isn't one of the stores we support, it might be a key or cert by itself
        } else if (isPemParsable(type, fileName)) {
            //This is the catch all case for PEM, P7B, etc. with common file extensions if the mime type isn't read correctly in the browser
            Reader reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
            PEMParser pemParser = new PEMParser(reader);
            Object object;
            boolean setEntry = false;
            while ((object = pemParser.readObject()) != null) {
                if (object instanceof PEMEncryptedKeyPair || object instanceof PEMKeyPair) {
                    PEMKeyPair pemKeyPair;
                    if (object instanceof PEMEncryptedKeyPair) {
                        PEMEncryptedKeyPair pemEncryptedKeyPairKeyPair = (PEMEncryptedKeyPair) object;
                        JcePEMDecryptorProviderBuilder jcePEMDecryptorProviderBuilder = new JcePEMDecryptorProviderBuilder();
                        pemKeyPair = pemEncryptedKeyPairKeyPair.decryptKeyPair(
                                jcePEMDecryptorProviderBuilder.build(keyPassword.toCharArray()));
                    } else {
                        pemKeyPair = (PEMKeyPair) object;
                    }

                    KeyPair keyPair = new JcaPEMKeyConverter().setProvider("BC").getKeyPair(pemKeyPair);
                    PrivateKey privateKey = keyPair.getPrivate();
                    Certificate[] chain = store.getCertificateChain(alias);
                    if (chain == null) {
                        chain = buildCertChain(alias, store);
                    }
                    store.setKeyEntry(alias, privateKey, keyPassword.toCharArray(), chain);
                    setEntry = true;
                } else if (object instanceof X509CertificateHolder) {
                    X509CertificateHolder x509CertificateHolder = (X509CertificateHolder) object;
                    CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509", "BC");
                    Certificate certificate = certificateFactory
                            .generateCertificate(new ByteArrayInputStream(x509CertificateHolder.getEncoded()));
                    X500Name x500name = new JcaX509CertificateHolder((X509Certificate) certificate)
                            .getSubject();
                    RDN cn = x500name.getRDNs(BCStyle.CN)[0];
                    String cnStr = IETFUtils.valueToString(cn.getFirst().getValue());
                    if (!store.isCertificateEntry(cnStr) && !store.isKeyEntry(cnStr)) {
                        store.setCertificateEntry(cnStr, certificate);
                    }
                    store.setCertificateEntry(alias, certificate);
                    setEntry = true;
                } else if (object instanceof ContentInfo) {
                    ContentInfo contentInfo = (ContentInfo) object;
                    if (contentInfo.getContentType().equals(CMSObjectIdentifiers.envelopedData)) {
                        CMSEnvelopedData cmsEnvelopedData = new CMSEnvelopedData(contentInfo);
                        OriginatorInfo originatorInfo = cmsEnvelopedData.getOriginatorInfo().toASN1Structure();
                        ASN1Set certificates = originatorInfo.getCertificates();
                        setEntry = importASN1CertificatesToStore(store, setEntry, certificates);
                    } else if (contentInfo.getContentType().equals(CMSObjectIdentifiers.signedData)) {
                        SignedData signedData = SignedData.getInstance(contentInfo.getContent());
                        ASN1Set certificates = signedData.getCertificates();
                        setEntry = importASN1CertificatesToStore(store, setEntry, certificates);
                    }
                } else if (object instanceof PKCS8EncryptedPrivateKeyInfo) {
                    PKCS8EncryptedPrivateKeyInfo pkcs8EncryptedPrivateKeyInfo = (PKCS8EncryptedPrivateKeyInfo) object;
                    Certificate[] chain = store.getCertificateChain(alias);
                    if (chain == null) {
                        chain = buildCertChain(alias, store);
                    }
                    try {
                        store.setKeyEntry(alias, pkcs8EncryptedPrivateKeyInfo.getEncoded(), chain);
                        setEntry = true;
                    } catch (KeyStoreException keyEx) {
                        try {
                            PKCS8Key pkcs8Key = new PKCS8Key(pkcs8EncryptedPrivateKeyInfo.getEncoded(),
                                    keyPassword.toCharArray());
                            store.setKeyEntry(alias, pkcs8Key.getPrivateKey(), keyPassword.toCharArray(),
                                    chain);
                            setEntry = true;
                        } catch (GeneralSecurityException e) {
                            LOGGER.error(
                                    "Unable to add PKCS8 key to keystore with secondary method. Throwing original exception.",
                                    e);
                            throw keyEx;
                        }
                    }
                }
            }
            if (setEntry) {
                fos = Files.newOutputStream(storeFile);
                store.store(fos, storepass.toCharArray());
            }
        }
    } catch (Exception e) {
        LOGGER.error("Unable to add entry {} to store", alias, e);
        throw new KeystoreEditorException("Unable to add entry " + alias + " to store", e);
    } finally {
        if (fos != null) {
            try {
                fos.close();
            } catch (IOException ignore) {
            }
        }
    }
    init();
}

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

@GET
@Path("/workspace/listFiles")
@Produces("application/json")
public Response filesInPath(@QueryParam("path") String path) {
    try {/* w  ww .  j av a  2  s. co m*/
        java.nio.file.Path pathLocation = Paths
                .get(new String(Base64.getDecoder().decode(path), Charset.defaultCharset()));
        return Response.status(Response.Status.OK).entity(workspace.listFilesInPath(pathLocation))
                .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();
    }
}