Example usage for org.apache.commons.codec.binary Base64 Base64

List of usage examples for org.apache.commons.codec.binary Base64 Base64

Introduction

In this page you can find the example usage for org.apache.commons.codec.binary Base64 Base64.

Prototype

public Base64() 

Source Link

Document

Creates a Base64 codec used for decoding (all modes) and encoding in URL-unsafe mode.

Usage

From source file:com.wwpass.connection.WWPassConnection.java

private static PKCS8EncodedKeySpec readKeyFile(String path) throws IOException {
    FileInputStream stream = new FileInputStream(new File(path));
    try {//w  w  w.j  a v  a2 s.com
        FileChannel fc = stream.getChannel();
        MappedByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size());
        String pem = Charset.defaultCharset().decode(bb).toString();
        pem = pem.replaceFirst("-----BEGIN (RSA )?PRIVATE KEY-----\r?\n?", "")
                .replace("-----END (RSA )?PRIVATE KEY-----", "");
        Base64 dec1 = new Base64();
        byte[] encoded = dec1.decode(pem);
        return new PKCS8EncodedKeySpec(encoded);
    } finally {
        stream.close();
    }
}

From source file:ca.sqlpower.wabit.dao.WorkspaceXMLDAO.java

private void saveWabitImage(WabitImage wabitImage) {
    xml.print(out, "<wabit-image");
    printCommonAttributes(wabitImage);/*from  w  w w. j a  va2 s.c o  m*/
    xml.niprint(out, ">");
    xml.indent++;

    final Image wabitInnerImage = wabitImage.getImage();
    if (wabitInnerImage != null) {
        ByteArrayOutputStream byteStream = PersisterUtils.convertImageToStreamAsPNG(wabitInnerImage);
        out.flush();
        byte[] byteArray = new Base64().encode(byteStream.toByteArray());
        logger.debug("Encoded length is " + byteArray.length);
        logger.debug("Stream has byte array " + Arrays.toString(byteStream.toByteArray()));
        for (int i = 0; i < byteArray.length; i++) {
            out.write((char) byteArray[i]);
            if (i % 60 == 59) {
                out.write("\n");
            }
        }
    }

    xml.indent--;
    xml.println(out, "</wabit-image>");
}

From source file:com.wwpass.connection.WWPassConnection.java

private static InputStream getReplyData(final InputStream rawXMLInput)
        throws IOException, WWPassProtocolException {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    Document dom;//from ww  w. j av  a  2 s.  c o  m
    InputStream is = null;

    try {
        DocumentBuilder db = dbf.newDocumentBuilder();

        is = rawXMLInput;

        dom = db.parse(is);

        Element docEle = dom.getDocumentElement();

        Node result = docEle.getElementsByTagName("result").item(0);
        boolean res = result.getTextContent().equalsIgnoreCase("true");

        Element data = (Element) docEle.getElementsByTagName("data").item(0);
        String encoding = data.getAttributes().getNamedItem("encoding").getTextContent();
        String strData;
        byte[] bb;
        if ("base64".equalsIgnoreCase(encoding)) {
            bb = (new Base64()).decode(data.getTextContent());
            strData = new String(bb, Charset.forName("UTF-8"));
            if (!res) {
                throw new WWPassProtocolException("SPFE returned error: " + strData);
            }
            return new ByteArrayInputStream(bb);
        } else {
            strData = data.getTextContent();
            if (!res) {
                throw new WWPassProtocolException("SPFE returned error: " + strData);
            }
            return new ByteArrayInputStream(strData.getBytes());
        }

    } catch (ParserConfigurationException pce) {
        throw new WWPassProtocolException("Malformed SPFE reply: " + pce.getMessage());
    } catch (SAXException se) {
        throw new WWPassProtocolException("Malformed SPFE reply: " + se.getMessage());
    } finally {
        if (is != null) {
            is.close();
        }
    }
}

From source file:android.core.SSLSocketTest.java

/**
 * Loads a keystore from a base64-encoded String. Returns the KeyManager[]
 * for the result.//from   w w w .j a  v  a2s .c  o  m
 */
private KeyManager[] getKeyManagers(String keys) throws Exception {
    byte[] bytes = new Base64().decode(keys.getBytes());
    InputStream inputStream = new ByteArrayInputStream(bytes);

    KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
    keyStore.load(inputStream, PASSWORD.toCharArray());
    inputStream.close();

    String algorithm = KeyManagerFactory.getDefaultAlgorithm();
    KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(algorithm);
    keyManagerFactory.init(keyStore, PASSWORD.toCharArray());

    return keyManagerFactory.getKeyManagers();
}

From source file:com.ah.ui.actions.home.clientManagement.service.CertificateGenSV.java

public static void genRadiusServerCert(String customerId, String hmId, String domain, String fileName,
        String certType, String certName) {
    String cerDic = BeAdminCentOSTools.AH_CERTIFICAT_PFEFIX + domain + BeAdminCentOSTools.AH_CERTIFICATE_HOME
            + File.separator;/*from  w w  w.  j  a  v a  2 s.  c  o  m*/
    try {
        CertificateGenSV cerSV = new CertificateGenSV();
        IResponseFromMDM res = new ResponseFromMDMImpl();
        HmBeAdminUtil.createServerCSR(cerSV.createCsrData(domain, fileName));
        String csrContent = cerSV.readFile(cerDic + fileName + ".csr");
        String csrTem = cerSV.transCsrCertificateToXML(customerId, hmId, certType, csrContent);
        ResponseModel csrRes = res.sendInfoToMDM(getUrl() + CERT_URI, csrTem);
        SignedCertificateEBO sce = cerSV.transResponseToSignedCertificate(csrRes);
        byte[] sc = new Base64().decode(sce.getCertPayload());
        cerSV.writeFile(cerDic + certName, new String(sc));
    } catch (Exception e) {
        e.printStackTrace();
    }

}

From source file:com.wwpass.connection.WWPassConnection.java

public WWPassConnection(X509Certificate cert, PKCS8EncodedKeySpec key, int timeoutSec, String spfeAddr)
        throws IOException, GeneralSecurityException {
    timeoutMs = timeoutSec * 1000;/* w  ww  .  j a va 2  s  .  c  om*/
    SpfeURL = "https://" + spfeAddr + "/";
    // Setting up client certificate and key

    X509Certificate[] chain = { cert };

    KeyFactory kf = KeyFactory.getInstance("RSA");
    PrivateKey privKey = kf.generatePrivate(key);

    KeyStore.PrivateKeyEntry pke = new KeyStore.PrivateKeyEntry(privKey, chain);

    //This adds no security but Java requires to password-protect the key
    byte[] password_bytes = new byte[16];
    (new java.security.SecureRandom()).nextBytes(password_bytes);
    // String password = (new BASE64Encoder()).encode(password_bytes);
    String password = (new Base64()).encodeToString(password_bytes);

    KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance("SunX509");
    KeyStore keyStore = KeyStore.getInstance("PKCS12");
    keyStore.load(null);

    keyStore.setEntry("WWPass client key", pke, new KeyStore.PasswordProtection(password.toCharArray()));
    keyManagerFactory.init(keyStore, password.toCharArray());

    SPFEContext = SSLContext.getInstance("TLS");

    // Making rootCA certificate
    InputStream is = null;
    CertificateFactory cf;
    X509Certificate rootCA = null;
    try {
        is = new ByteArrayInputStream(WWPassCA_DER);
        cf = CertificateFactory.getInstance("X.509");
        rootCA = (X509Certificate) cf.generateCertificate(is);
    } finally {
        if (is != null) {
            is.close();
        }
    }

    //Creating TrustManager for this CA
    TrustManagerFactory trustManagerFactory = TrustManagerFactory
            .getInstance(TrustManagerFactory.getDefaultAlgorithm());

    KeyStore ks = KeyStore.getInstance("JKS");
    ks.load(null);
    ks.setCertificateEntry("WWPass Root CA", rootCA);

    trustManagerFactory.init(ks);

    SPFEContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(),
            new java.security.SecureRandom());
}

From source file:net.jakobnielsen.imagga.upload.client.UploadClientIntegrationTest.java

public static File createTestFile() throws IOException {
    Base64 decoder = new Base64();
    byte[] imgBytes = decoder.decode(UploadClientIntegrationTest.TEST_IMAGE);
    File f = File.createTempFile("imagga", ".png");
    FileOutputStream osf = new FileOutputStream(f);
    osf.write(imgBytes);/*from w w w.  j av  a 2s  .  c  o  m*/
    osf.flush();
    return f;
}

From source file:com.viettel.hqmc.DAO.FilesExpandDAO.java

public String onCreatePaperByLeaderForAA() {
    try {//from www  .j  ava 2  s .c o m
        Base64 decoder = new Base64();
        String title = new String(
                decoder.decode(getRequest().getParameter("title").replace("_", "+").getBytes()), "UTF-8");
        String content = new String(
                decoder.decode(getRequest().getParameter("content").replace("_", "+").getBytes()), "UTF-8");
        FilesExpandDAOHE fdhe = new FilesExpandDAOHE();
        FilesDAO fdao = new FilesDAO();
        createForm.setTitleEditATTP(title);
        createForm.setContentsEditATTP(content);
        boolean bReturn = fdhe.onCreatePaperForAA(createForm, getDepartmentId(), getDepartment().getDeptName(),
                getUserId(), getUserName());
        List resultMessage = new ArrayList();
        if (bReturn) {
            resultMessage.add("1");
            resultMessage.add("Lu d liu thnh cng");
            if (createForm.getStatus().equals(Constants.FILE_STATUS.APPROVED)) {
                fdao.getBarcode(createForm);
            }
        } else {
            resultMessage.add("3");
            resultMessage.add("Lu d liu khng thnh cng");
        }
        jsonDataGrid.setItems(resultMessage);
        return GRID_DATA;
    } catch (UnsupportedEncodingException ex) {
        LogUtil.addLog(ex);//binhnt sonar a160901
        //            Logger.getLogger(FilesExpandDAO.class.getName()).log(Level.SEVERE, null, ex);
    }
    return GRID_DATA;
}

From source file:net.bioclipse.ds.sdk.pdewizard.DSTemplate.java

/**
 * This method duplicates the encoding in the CDKFingerPrintPropertyCalculator. 
 * This is required to read it back into 1024 bits.
 * @param value//from  w  w  w.  j a va  2s.co  m
 * @return
 */
public String encodeFPBase64(Object value) {
    if (value instanceof String)
        return (String) value;
    BitSet val = (BitSet) value;
    byte[] bytes = new byte[val.length() / 8 + 1];
    for (int i = 0; i < val.length(); i++) {
        if (val.get(i)) {
            bytes[bytes.length - i / 8 - 1] |= 1 << (i % 8);
        }
    }
    return new String(new Base64().encode(bytes));
}

From source file:io.hops.hopsworks.api.project.DataSetService.java

@GET
@Path("filePreview/{path: .+}")
@Produces(MediaType.APPLICATION_JSON)//from  w w w  .  j a v a2 s .  co  m
@AllowedProjectRoles({ AllowedProjectRoles.DATA_SCIENTIST, AllowedProjectRoles.DATA_OWNER })
public Response filePreview(@PathParam("path") String path, @QueryParam("mode") String mode,
        @Context SecurityContext sc) throws DatasetException, ProjectException {
    Users user = userFacade.findByEmail(sc.getUserPrincipal().getName());
    String username = hdfsUsersBean.getHdfsUserName(project, user);

    DsPath dsPath = pathValidator.validatePath(this.project, path);
    dsPath.validatePathExists(inodes, false);
    org.apache.hadoop.fs.Path fullPath = dsPath.getFullPath();
    String fileName = fullPath.getName();

    DistributedFileSystemOps udfso = null;
    FSDataInputStream is = null;

    RESTApiJsonResponse json = new RESTApiJsonResponse();
    try {
        udfso = dfs.getDfsOps(username);

        //tests if the user have permission to access this path
        is = udfso.open(fullPath);

        //Get file type first. If it is not a known image type, display its 
        //binary contents instead
        String fileExtension = "txt"; // default file  type
        //Check if file contains a valid extension
        if (fileName.contains(".")) {
            fileExtension = fileName.substring(fileName.lastIndexOf(".")).replace(".", "").toUpperCase();
        }
        long fileSize = udfso.getFileStatus(fullPath).getLen();

        FilePreviewDTO filePreviewDTO = null;
        if (HopsUtils.isInEnum(fileExtension, FilePreviewImageTypes.class)) {
            //If it is an image smaller than 10MB download it otherwise thrown an error
            if (fileSize < settings.getFilePreviewImageSize()) {
                //Read the image in bytes and convert it to base64 so that is 
                //rendered properly in the front-end
                byte[] imageInBytes = new byte[(int) fileSize];
                is.readFully(imageInBytes);
                String base64Image = new Base64().encodeAsString(imageInBytes);
                filePreviewDTO = new FilePreviewDTO(Settings.FILE_PREVIEW_IMAGE_TYPE,
                        fileExtension.toLowerCase(), base64Image);
            } else {
                throw new DatasetException(RESTCodes.DatasetErrorCode.IMAGE_SIZE_INVALID, Level.FINE);
            }
        } else {
            try (DataInputStream dis = new DataInputStream(is)) {
                int sizeThreshold = Settings.FILE_PREVIEW_TXT_SIZE_BYTES; //in bytes
                if (fileSize > sizeThreshold && !fileName.endsWith(Settings.README_FILE)
                        && mode.equals(Settings.FILE_PREVIEW_MODE_TAIL)) {
                    dis.skipBytes((int) (fileSize - sizeThreshold));
                } else if (fileName.endsWith(Settings.README_FILE)
                        && fileSize > Settings.FILE_PREVIEW_TXT_SIZE_BYTES) {
                    throw new DatasetException(RESTCodes.DatasetErrorCode.FILE_PREVIEW_ERROR, Level.FINE);
                } else if ((int) fileSize < sizeThreshold) {
                    sizeThreshold = (int) fileSize;
                }
                byte[] headContent = new byte[sizeThreshold];
                dis.readFully(headContent, 0, sizeThreshold);
                //File content
                filePreviewDTO = new FilePreviewDTO(Settings.FILE_PREVIEW_TEXT_TYPE,
                        fileExtension.toLowerCase(), new String(headContent));
            }
        }

        json.setData(filePreviewDTO);
    } catch (IOException ex) {
        throw new DatasetException(RESTCodes.DatasetErrorCode.DATASET_OPERATION_ERROR, Level.SEVERE,
                "path: " + path, ex.getMessage(), ex);
    } finally {
        if (is != null) {
            try {
                is.close();
            } catch (IOException ex) {
                LOGGER.log(Level.SEVERE, "Error while closing stream.", ex);
            }
        }
        if (udfso != null) {
            dfs.closeDfsClient(udfso);
        }
    }

    return noCacheResponse.getNoCacheResponseBuilder(Response.Status.OK).entity(json).build();
}