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.googlesource.gerrit.plugins.gitblit.auth.GerritAuthFilter.java

public boolean filterBasicAuth(HttpServletRequest request, HttpServletResponse response, String hdr)
        throws IOException, UnsupportedEncodingException {
    if (!hdr.startsWith(LIT_BASIC)) {
        response.setHeader("WWW-Authenticate", "Basic realm=\"Gerrit Code Review\"");
        response.sendError(SC_UNAUTHORIZED);
        return false;
    }//w w w.  ja v  a2 s . co m

    final byte[] decoded = new Base64().decode(hdr.substring(LIT_BASIC.length()).getBytes());
    String usernamePassword = new String(decoded,
            Objects.firstNonNull(request.getCharacterEncoding(), "UTF-8"));
    int splitPos = usernamePassword.indexOf(':');
    if (splitPos < 1) {
        response.setHeader("WWW-Authenticate", "Basic realm=\"Gerrit Code Review\"");
        response.sendError(SC_UNAUTHORIZED);
        return false;
    }
    request.setAttribute("gerrit-username", usernamePassword.substring(0, splitPos));
    request.setAttribute("gerrit-password", usernamePassword.substring(splitPos + 1));

    return true;
}

From source file:com.sldeditor.common.property.EncryptedPropertiesApache.java

@Override
public synchronized String decrypt(String str) {
    byte[] dec;/* w ww . j av  a  2s  .  c  om*/
    try {
        dec = new Base64().decode(str.getBytes());
        byte[] utf8 = decrypter.doFinal(dec);
        return new String(utf8, "UTF-8");
    } catch (IOException e) {
        e.printStackTrace();
    } catch (IllegalBlockSizeException e) {
        e.printStackTrace();
    } catch (BadPaddingException e) {
        e.printStackTrace();
    }

    return str;
}

From source file:auth.ProcessResponseServlet.java

private String decodeAuthnRequestXML(String encodedRequestXmlString) throws SamlException {
    try {//from ww  w  .j a  v a 2s.  co  m
        // URL decode
        // No need to URL decode: auto decoded by request.getParameter() method

        // Base64 decode
        Base64 base64Decoder = new Base64();
        byte[] xmlBytes = encodedRequestXmlString.getBytes("UTF-8");
        byte[] base64DecodedByteArray = base64Decoder.decode(xmlBytes);

        //Uncompress the AuthnRequest data
        //First attempt to unzip the byte array according to DEFLATE (rfc 1951)
        try {

            Inflater inflater = new Inflater(true);
            inflater.setInput(base64DecodedByteArray);
            // since we are decompressing, it's impossible to know how much space we
            // might need; hopefully this number is suitably big
            byte[] xmlMessageBytes = new byte[5000];
            int resultLength = inflater.inflate(xmlMessageBytes);

            if (!inflater.finished()) {
                throw new RuntimeException("didn't allocate enough space to hold " + "decompressed data");
            }

            inflater.end();
            return new String(xmlMessageBytes, 0, resultLength, "UTF-8");

        } catch (DataFormatException e) {

            // if DEFLATE fails, then attempt to unzip the byte array according to
            // zlib (rfc 1950)
            ByteArrayInputStream bais = new ByteArrayInputStream(base64DecodedByteArray);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            InflaterInputStream iis = new InflaterInputStream(bais);
            byte[] buf = new byte[1024];
            int count = iis.read(buf);
            while (count != -1) {
                baos.write(buf, 0, count);
                count = iis.read(buf);
            }
            iis.close();
            return new String(baos.toByteArray());
        }

    } catch (UnsupportedEncodingException e) {
        throw new SamlException("Error decoding AuthnRequest: " + "Check decoding scheme - " + e.getMessage());
    } catch (IOException e) {
        throw new SamlException("Error decoding AuthnRequest: " + "Check decoding scheme - " + e.getMessage());
    }
}

From source file:jatran.stub.StringUtil.java

/**
 * Decodes a string which was encoded using Base64 encoding.
 *
 * @param str The string to decode//w  ww  . j  a  v  a 2s.  co m
 * @return Decoded string
 */
public static String decodeString(String str) {
    Base64 decoder = new Base64();
    return new String(decoder.decode(str.getBytes()));
}

From source file:fr.gael.dhus.datastore.scanner.ODataScanner.java

@Override
public int scan() throws InterruptedException {
    // Workaround: transferring 1 product. see l.50
    if (this.client == null) {
        try {/*  w  w w .jav a 2  s  .  c  o  m*/
            URL url = new URL(this.uri);
            HttpURLConnection co = (HttpURLConnection) url.openConnection();

            // HTTP Basic Authentication.
            String userpass = this.username + ":" + this.password;
            String basicAuth = "Basic " + new String(new Base64().encode(userpass.getBytes()));
            co.setRequestProperty("Authorization", basicAuth);

            co.connect();
            String cd = co.getHeaderField("Content-Disposition");
            co.disconnect();

            Matcher m = Pattern.compile(".*?filename=\"(.*?)\\.zip\".*?").matcher((cd));
            if (!m.matches())
                throw new Exception("filename not in header");

            String filename = m.group(1);

            //url = new URIBuilder (url.toURI ())
            //   .setUserInfo (this.username, this.password).build ().toURL ();

            this.getScanList().add(new URLExt(url, false, filename));
        } catch (Exception e) {
            LOGGER.error("failed to transfer " + this.uri, e);
            return 0;
        }
        return 1;
    }

    // The actual scan() code.
    int res = 0;

    try {
        // Prepare OData request, we want Products.
        String resource_path = new String("/Products");
        Facets facets = (new Facets()).setNullable(false);
        Map<String, String> query_params = new HashMap<>();

        long now = System.currentTimeMillis();
        EdmSimpleType type = RuntimeDelegate.getEdmSimpleType(DateTime);

        // Filtering by ingestionDate.
        if (this.lastScanTime != 0L) {
            StringBuilder sb = new StringBuilder("IngestionDate ge ");
            Date l_time = new Date(this.lastScanTime);
            sb.append(type.valueToString(l_time, EdmLiteralKind.URI, facets));

            sb.append(" and IngestionDate lt ");
            l_time = new Date(now);
            sb.append(type.valueToString(l_time, EdmLiteralKind.URI, facets));
            query_params.put("$filter", sb.toString());
        } else {
            Date l_time = new Date(now);
            String value = "IngestionDate lt " + type.valueToString(l_time, EdmLiteralKind.URI, facets);

            query_params.put("$filter", value);
        }

        // Ordering by ingestionDate.
        query_params.put("$orderby", "IngestionDate");

        // Pagination.
        int page_len = 50; // TODO get this value from config.
        query_params.put("$top", String.valueOf(page_len));

        try {
            for (long i = 0;; i++) {
                if (i != 0)
                    query_params.put("$skip", String.valueOf(page_len * i));

                ODataFeed of = this.client.readFeed(resource_path, query_params);

                for (ODataEntry entry : of.getEntries()) {
                    String pdt_name = (String) entry.getProperties().get("Name");
                    if (this.getUserPattern() == null || this.getUserPattern().matcher(pdt_name).matches()) {
                        String key = (String) entry.getProperties().get("Id");
                        URL url = new URIBuilder(
                                this.client.getServiceRoot() + "/Products" + "('" + key + "')/$value")
                                        .setUserInfo(this.username, this.password).build().toURL();

                        this.getScanList().add(new URLExt(url, false, pdt_name));

                        res += 1;
                    }
                }

                if (of.getEntries().size() != page_len) // End of pagination.
                    break;
            }
        } catch (ODataException | IOException | URISyntaxException e) {
            LOGGER.error("Product retrieval failed", e);
        }

        this.lastScanTime = now;
    } catch (ODataException e) {
        LOGGER.error(e);
    }

    return res;
}

From source file:com.forsrc.utils.AesUtils.java

/**
 * Decrypt string.//w  ww  .  j a  v  a2s  .c om
 *
 * @param code the code
 * @return String string
 * @throws AesException the aes exception
 * @Title: decrypt
 * @Description:
 */
public String decrypt(String code) throws AesException {

    byte[] raw = null;
    try {
        raw = KEY.getBytes(CHARSET_ASCII);
    } catch (UnsupportedEncodingException e) {
        throw new AesException(e);
    }

    SecretKeySpec skeySpec = new SecretKeySpec(raw, SECRET_KEY);

    Cipher cipher = null;
    try {
        cipher = Cipher.getInstance(CIPHER_KEY);
    } catch (NoSuchAlgorithmException e) {
        throw new AesException(e);
    } catch (NoSuchPaddingException e) {
        throw new AesException(e);
    }

    IvParameterSpec iv = new IvParameterSpec(IV_PARAMETER.getBytes());

    try {
        cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
    } catch (InvalidKeyException e) {
        throw new AesException(e);
    } catch (InvalidAlgorithmParameterException e) {
        throw new AesException(e);
    }

    byte[] encrypted = null;
    try {
        encrypted = new Base64().decode(code);
    } catch (Exception e) {
        throw new AesException(e);
    }

    byte[] original = null;
    try {
        original = cipher.doFinal(encrypted);
    } catch (IllegalBlockSizeException e) {
        throw new AesException(e);
    } catch (BadPaddingException e) {
        throw new AesException(e);
    }

    try {
        return new String(original, CHARSET_UTF8);
    } catch (UnsupportedEncodingException e) {
        throw new AesException(e);
    }

}

From source file:com.google.caja.plugin.DataUriFetcher.java

public final byte[] fetchBinary(ExternalReference ref, String mimeType) throws UriFetchException {
    URI uri = ref.getUri();/*  www  .ja  va 2  s .c  o m*/
    if (!isDataUri(uri)) {
        throw new UriFetchException(ref, mimeType);
    }

    String dataUri = uri.getSchemeSpecificPart();
    // We split the data uri into the mimetype and the data portion by
    // searching for the first comma (whether encoded or not).  This is
    // not a complete parse of data URIs - specifically if the mime-type
    // contains a comma
    Matcher m = DATA_URI_RE.matcher(dataUri);
    if (m.find()) {
        try {
            String charset = charsetFromMime(m.group(DATA_URI.TYPE.ordinal()));
            boolean base64 = null != m.group(DATA_URI.BASE64.ordinal());
            byte[] encoded = m.group(DATA_URI.DATA.ordinal()).getBytes(charset);
            byte[] decoded = base64 ? new Base64().decode(encoded) : encoded;
            return decoded;
        } catch (UnsupportedEncodingException e) {
            throw new UriFetcher.UriFetchException(ref, mimeType, e);
        }
    }
    throw new UriFetcher.UriFetchException(ref, mimeType);
}

From source file:fi.aalto.seqpig.io.QseqStorer.java

@Override
public void putNext(Tuple f) throws IOException {

    if (allQseqFieldNames == null) {
        try {/*from ww  w.j  av  a  2s. c  om*/
            //BASE64Decoder decode = new BASE64Decoder();
            Base64 codec = new Base64();
            Properties p = UDFContext.getUDFContext().getUDFProperties(this.getClass());
            String datastr = p.getProperty("allQseqFieldNames");
            //byte[] buffer = decode.decodeBuffer(datastr);
            byte[] buffer = codec.decodeBase64(datastr);
            ByteArrayInputStream bstream = new ByteArrayInputStream(buffer);
            ObjectInputStream ostream = new ObjectInputStream(bstream);

            allQseqFieldNames = (HashMap<String, Integer>) ostream.readObject();
        } catch (ClassNotFoundException e) {
            throw new IOException(e);
        }
    }

    SequencedFragment fastqrec = new SequencedFragment();
    int index;

    index = getFieldIndex("instrument", allQseqFieldNames);
    if (index > -1 && DataType.findType(f.get(index)) == DataType.CHARARRAY) {
        fastqrec.setInstrument((String) f.get(index));
    }

    index = getFieldIndex("run_number", allQseqFieldNames);
    if (index > -1 && DataType.findType(f.get(index)) == DataType.INTEGER) {
        fastqrec.setRunNumber(((Integer) f.get(index)));
    }

    index = getFieldIndex("flow_cell_id", allQseqFieldNames);
    if (index > -1 && DataType.findType(f.get(index)) == DataType.CHARARRAY) {
        fastqrec.setFlowcellId((String) f.get(index));
    }

    index = getFieldIndex("lane", allQseqFieldNames);
    if (index > -1 && DataType.findType(f.get(index)) == DataType.INTEGER) {
        fastqrec.setLane(((Integer) f.get(index)));
    }

    index = getFieldIndex("tile", allQseqFieldNames);
    if (index > -1 && DataType.findType(f.get(index)) == DataType.INTEGER) {
        fastqrec.setTile(((Integer) f.get(index)));
    }

    index = getFieldIndex("xpos", allQseqFieldNames);
    if (index > -1 && DataType.findType(f.get(index)) == DataType.INTEGER) {
        fastqrec.setXpos(((Integer) f.get(index)));
    }

    index = getFieldIndex("ypos", allQseqFieldNames);
    if (index > -1 && DataType.findType(f.get(index)) == DataType.INTEGER) {
        fastqrec.setYpos(((Integer) f.get(index)));
    }

    index = getFieldIndex("read", allQseqFieldNames);
    if (index > -1 && DataType.findType(f.get(index)) == DataType.INTEGER) {
        fastqrec.setRead(((Integer) f.get(index)));
    }

    index = getFieldIndex("qc_passed", allQseqFieldNames);
    if (index > -1 && DataType.findType(f.get(index)) == DataType.BOOLEAN) {
        fastqrec.setFilterPassed(((Boolean) f.get(index)));
    }

    index = getFieldIndex("control_number", allQseqFieldNames);
    if (index > -1 && DataType.findType(f.get(index)) == DataType.INTEGER) {
        fastqrec.setControlNumber(((Integer) f.get(index)));
    }

    index = getFieldIndex("index_sequence", allQseqFieldNames);
    if (index > -1 && DataType.findType(f.get(index)) == DataType.CHARARRAY) {
        fastqrec.setIndexSequence((String) f.get(index));
    }

    index = getFieldIndex("sequence", allQseqFieldNames);
    if (index > -1 && DataType.findType(f.get(index)) == DataType.CHARARRAY) {
        fastqrec.setSequence(new Text((String) f.get(index)));
    }

    index = getFieldIndex("quality", allQseqFieldNames);
    if (index > -1 && DataType.findType(f.get(index)) == DataType.CHARARRAY) {
        fastqrec.setQuality(new Text((String) f.get(index)));
    }

    try {
        writer.write(null, fastqrec);
    } catch (InterruptedException e) {
        throw new IOException(e);
    }
}

From source file:fi.aalto.seqpig.io.FastqStorer.java

@Override
public void putNext(Tuple f) throws IOException {
    if (allFastqFieldNames == null) {
        try {//from w w w  . ja va 2s. c o  m
            //BASE64Decoder decode = new BASE64Decoder();
            Base64 codec = new Base64();
            Properties p = UDFContext.getUDFContext().getUDFProperties(this.getClass());
            String datastr = p.getProperty("allFastqFieldNames");
            //byte[] buffer = decode.decodeBuffer(datastr);
            byte[] buffer = codec.decodeBase64(datastr);
            ByteArrayInputStream bstream = new ByteArrayInputStream(buffer);
            ObjectInputStream ostream = new ObjectInputStream(bstream);

            allFastqFieldNames = (HashMap<String, Integer>) ostream.readObject();
        } catch (ClassNotFoundException e) {
            throw new IOException(e);
        }
    }

    SequencedFragment fastqrec = new SequencedFragment();
    int index;

    index = getFieldIndex("instrument", allFastqFieldNames);
    if (index > -1 && DataType.findType(f.get(index)) == DataType.CHARARRAY) {
        fastqrec.setInstrument((String) f.get(index));
    }

    index = getFieldIndex("run_number", allFastqFieldNames);
    if (index > -1 && DataType.findType(f.get(index)) == DataType.INTEGER) {
        fastqrec.setRunNumber(((Integer) f.get(index)));
    }

    index = getFieldIndex("flow_cell_id", allFastqFieldNames);
    if (index > -1 && DataType.findType(f.get(index)) == DataType.CHARARRAY) {
        fastqrec.setFlowcellId((String) f.get(index));
    }

    index = getFieldIndex("lane", allFastqFieldNames);
    if (index > -1 && DataType.findType(f.get(index)) == DataType.INTEGER) {
        fastqrec.setLane(((Integer) f.get(index)));
    }

    index = getFieldIndex("tile", allFastqFieldNames);
    if (index > -1 && DataType.findType(f.get(index)) == DataType.INTEGER) {
        fastqrec.setTile(((Integer) f.get(index)));
    }

    index = getFieldIndex("xpos", allFastqFieldNames);
    if (index > -1 && DataType.findType(f.get(index)) == DataType.INTEGER) {
        fastqrec.setXpos(((Integer) f.get(index)));
    }

    index = getFieldIndex("ypos", allFastqFieldNames);
    if (index > -1 && DataType.findType(f.get(index)) == DataType.INTEGER) {
        fastqrec.setYpos(((Integer) f.get(index)));
    }

    index = getFieldIndex("read", allFastqFieldNames);
    if (index > -1 && DataType.findType(f.get(index)) == DataType.INTEGER) {
        fastqrec.setRead(((Integer) f.get(index)));
    }

    index = getFieldIndex("qc_passed", allFastqFieldNames);
    if (index > -1 && DataType.findType(f.get(index)) == DataType.BOOLEAN) {
        fastqrec.setFilterPassed(((Boolean) f.get(index)));
    }

    index = getFieldIndex("control_number", allFastqFieldNames);
    if (index > -1 && DataType.findType(f.get(index)) == DataType.INTEGER) {
        fastqrec.setControlNumber(((Integer) f.get(index)));
    }

    index = getFieldIndex("index_sequence", allFastqFieldNames);
    if (index > -1 && DataType.findType(f.get(index)) == DataType.CHARARRAY) {
        fastqrec.setIndexSequence((String) f.get(index));
    }

    index = getFieldIndex("sequence", allFastqFieldNames);
    if (index > -1 && DataType.findType(f.get(index)) == DataType.CHARARRAY) {
        fastqrec.setSequence(new Text((String) f.get(index)));
    }

    index = getFieldIndex("quality", allFastqFieldNames);
    if (index > -1 && DataType.findType(f.get(index)) == DataType.CHARARRAY) {
        fastqrec.setQuality(new Text((String) f.get(index)));
    }

    try {
        writer.write(null, fastqrec);
    } catch (InterruptedException e) {
        throw new IOException(e);
    }
}

From source file:ch.cern.security.saml2.utils.xml.XMLUtils.java

public static String encode(String string) throws IOException, UnsupportedEncodingException {

    // Encoded the string in base64
    Base64 base64encoder = new Base64();
    String base64response = new String(base64encoder.encode(string.getBytes()), "UTF-8");

    return base64response;
}