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:Importers.ImportReportCompiler.java

private Vulnerability getVuln(Node vuln_node) {
    Base64 b64 = new Base64();
    Vulnerability vuln = new Vulnerability();

    String custom = "false";
    String category = "";
    String cvss_string = "";

    try {/*from  ww w. j av a 2  s.  c  om*/
        custom = vuln_node.getAttributes().getNamedItem("custom-risk").getTextContent();
    } catch (NullPointerException e) {
        ;
    }
    try {
        category = vuln_node.getAttributes().getNamedItem("category").getTextContent();
    } catch (NullPointerException e) {
        ;
    }
    try {
        cvss_string = vuln_node.getAttributes().getNamedItem("cvss").getTextContent();
    } catch (NullPointerException e) {
        ;
    }

    // TODO read identifiers
    //vuln.setIdentifier(vuln_node.getAttributes().getNamedItem("id").getTextContent());
    vuln.setIs_custom_risk(custom.equalsIgnoreCase("true"));
    vuln.setRisk_category(category);
    vuln.setCvss_vector_string(cvss_string);

    NodeList children = vuln_node.getChildNodes();
    for (int i = 0; i < children.getLength(); i++) {
        Node node = children.item(i);
        if (node.getNodeType() == Node.ELEMENT_NODE) {
            String name = node.getNodeName();
            String value = node.getTextContent();
            //System.out.println(name + ":" + value);

            if (name.equalsIgnoreCase("title")) {
                vuln.setTitle(new String(b64.decode(value)));
            } else if (name.equalsIgnoreCase("identifiers")) {
                NodeList identifiers = node.getChildNodes();
                for (int ii = 0; ii < identifiers.getLength(); ii++) {
                    Node idNode = identifiers.item(ii);
                    if (idNode.getNodeType() == Node.ELEMENT_NODE) {
                        String hash = idNode.getAttributes().getNamedItem("hash").getTextContent();
                        String import_tool = idNode.getAttributes().getNamedItem("import_tool")
                                .getTextContent();
                        vuln.setImport_tool(import_tool);
                        // this hash is a legacy broken from the before time
                        if (hash.equalsIgnoreCase("24d459a81449d721c8f9a86c2913034")) {
                            vuln.setIdentifier(); // this replaces the hash with the current MD5(vuln.getTitle());
                        } else {
                            vuln.setIdentifierFromSaveFile(hash, import_tool); // this trusts the source tool and hash.
                        }
                    }
                }

            } else if (name.equalsIgnoreCase("description")) {
                vuln.setDescription(new String(b64.decode(value)));
            } else if (name.equalsIgnoreCase("recommendation")) {
                vuln.setRecommendation(new String(b64.decode(value)));
            } else if (name.equalsIgnoreCase("affected-hosts")) {
                Vector affected_hosts = getHosts(node);
                vuln.addAffectedHosts(affected_hosts);
            } else if (name.equalsIgnoreCase("references")) {

                NodeList references = node.getChildNodes();
                for (int n = 0; n < references.getLength(); n++) {
                    Node refNode = references.item(n);
                    if (refNode.getNodeType() == Node.ELEMENT_NODE) {
                        String description = refNode.getAttributes().getNamedItem("description")
                                .getTextContent();
                        String url = refNode.getTextContent();
                        Reference ref = new Reference(description, url);
                        vuln.addReference(ref);
                    }

                }

            }

        }
    }

    // for original users with saved personal vulns saved without import tools
    if (vuln.getImport_tool() == "NULL") {
        vuln.setImport_tool("ReportCompiler");
        vuln.setIdentifier();
        System.out.println(vuln.getTitle() + ": hash: " + vuln.getIDsAsString());
    }

    return vuln;
}

From source file:at.uni_salzburg.cs.ckgroup.apos.AposNtripCasterMock.java

/**
 * Initialize the NTRIP mock caster.//from w  ww .  j a v  a2  s .c  o  m
 * @throws FileNotFoundException 
 */
private void init(Properties props) throws FileNotFoundException {

    port = Integer.parseInt(props.getProperty(AposNtrip.PROP_PORT));
    String userName = props.getProperty(AposNtrip.PROP_USERNAME);
    String password = props.getProperty(AposNtrip.PROP_PASSWORD);
    String mountPoint = props.getProperty(AposNtrip.PROP_MOUNTPOINT);

    byte[] encodedPassword = (userName + ":" + password).getBytes();
    Base64 encoder = new Base64();
    basicAuthentication = encoder.encode(encodedPassword);

    expectedRequest = "GET /" + mountPoint + " HTTP/1.0";
    expectedUserAgent = "User-Agent: .*";
    expectedAuthorisation = "Authorization: Basic " + (new String(basicAuthentication));
    expectedLocation = props.getProperty(PROP_EXPECTED_LOCATION);

    System.out.println("AposNtripCasterMock: expectedRequest=" + expectedRequest);
    System.out.println("AposNtripCasterMock: expectedUserAgent=" + expectedUserAgent);
    System.out.println("AposNtripCasterMock: expectedAuthorisation=" + expectedAuthorisation);

    String fileName = props.getProperty(PROP_INPUT_DATA_FILE);
    URL url = Thread.currentThread().getContextClassLoader().getResource(fileName);

    if (url == null)
        throw new FileNotFoundException(fileName);

    inputDataFile = new File(url.getFile());
}

From source file:com.shuffle.bitcoin.blockchain.Btcd.java

/**
 * This method takes in a transaction hash and returns a bitcoinj transaction object.
 *//*from  w w w.  jav a 2s .  c om*/
synchronized org.bitcoinj.core.Transaction getTransaction(String transactionHash) throws IOException {

    org.bitcoinj.core.Transaction tx = null;
    String requestBody = "{\"jsonrpc\":\"2.0\",\"id\":\"null\",\"method\":\"getrawtransaction\", \"params\":[\""
            + transactionHash + "\"]}";

    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setDoOutput(true);
    connection.setRequestMethod("POST");
    connection.setRequestProperty("Content-Type", "application/json");
    connection.setRequestProperty("Accept", "application/json");
    Base64 b = new Base64();
    String authString = rpcuser + ":" + rpcpass;
    String encoding = b.encodeAsString(authString.getBytes());
    connection.setRequestProperty("Authorization", "Basic " + encoding);
    connection.setRequestProperty("Content-Length", Integer.toString(requestBody.getBytes().length));
    connection.setDoInput(true);
    OutputStream out = connection.getOutputStream();
    out.write(requestBody.getBytes());

    if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
        InputStream is = connection.getInputStream();
        BufferedReader rd = new BufferedReader(new InputStreamReader(is));
        String line;
        StringBuffer response = new StringBuffer();
        while ((line = rd.readLine()) != null) {
            response.append(line);
            response.append('\r');
        }
        rd.close();

        JSONObject json = new JSONObject(response.toString());
        String hexTx = (String) json.get("result");
        HexBinaryAdapter adapter = new HexBinaryAdapter();
        byte[] bytearray = adapter.unmarshal(hexTx);
        Context context = Context.getOrCreate(netParams);
        tx = new org.bitcoinj.core.Transaction(netParams, bytearray);

    }

    out.flush();
    out.close();

    return tx;

}

From source file:com.googlesource.gerrit.plugins.gitblit.auth.GerritAuthenticationFilter.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  . j  a  va2 s .  c  o  m

    final byte[] decoded = new Base64().decode(hdr.substring(LIT_BASIC.length()).getBytes());
    String encoding = request.getCharacterEncoding();
    if (encoding == null) {
        encoding = "UTF-8";
    }
    String usernamePassword = new String(decoded, encoding);
    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.norbl.util.StringUtil.java

public static String decrypt(SecretKey key, String en) throws Exception {
    Base64 b64enc = new Base64();
    byte[] enb = b64enc.decode(en.getBytes());
    Cipher c = Cipher.getInstance("AES");
    c.init(Cipher.DECRYPT_MODE, key);
    byte[] denb = c.doFinal(enb);
    return (new String(denb));
}

From source file:com.sixsq.slipstream.cookie.CryptoUtils.java

static private String savePrivateKey(PrivateKey privateKey) throws GeneralSecurityException {
    KeyFactory fact = KeyFactory.getInstance(keyPairAlgorithm);
    PKCS8EncodedKeySpec spec = fact.getKeySpec(privateKey, PKCS8EncodedKeySpec.class);
    byte[] encoded = spec.getEncoded();
    String privateKeyStr = new Base64().encodeToString(encoded);
    return privateKeyStr;
}

From source file:de.extra.client.plugins.outputplugin.crypto.ExtraCryptoUtil.java

/** Decrypts the specified encrypted string, using the specified secret key. */
private static String decrypt(String sName, String secretKey) {
    if (secretKey == null) {
        secretKey = SYM_KEY_STR;//from w w w.  j a va  2  s.  co m
    }

    if (sName == null || sName.equals("")) {
        return "";
    }

    String sText = "";
    try {
        SecretKeySpec skeySpec = decodeKey(secretKey);
        Cipher decryptCipher = Cipher.getInstance(TRANSFORMATION);
        decryptCipher.init(Cipher.DECRYPT_MODE, skeySpec);

        byte[] encpArr = new Base64().decode(sName.trim());

        byte[] plainText = decryptCipher.doFinal(encpArr);

        sText = new String(plainText, CHARSET);
    } catch (Exception e) {
        e.printStackTrace(System.err);
    }

    return sText;
}

From source file:co.cask.hydrator.plugin.EncoderTest.java

@Test
public void testBase64StringEncoder() throws Exception {
    String test = "This is a test for testing base64 encoding";
    Transform<StructuredRecord, StructuredRecord> transform = new Encoder(
            new Encoder.Config("a:STRING_BASE64", OUTPUTSTR.toString()));
    transform.initialize(null);/*www  .j  ava  2s.  c  o m*/

    MockEmitter<StructuredRecord> emitter = new MockEmitter<>();
    transform.transform(StructuredRecord.builder(INPUT).set("a", test).set("b", "2").set("c", "3").set("d", "4")
            .set("e", "5").build(), emitter);

    Base64 base64 = new Base64();
    String expected = base64.encodeAsString(test.getBytes("UTF-8"));
    String actual = emitter.getEmitted().get(0).get("a");
    Assert.assertEquals(2, emitter.getEmitted().get(0).getSchema().getFields().size());
    Assert.assertEquals(expected, actual);
}

From source file:com.claresco.tinman.servlet.XapiServletUtility.java

protected static String decodeBase64(String theSecret) throws UnsupportedEncodingException {
    Base64 decoder = new Base64();

    byte[] decodedBytes = decoder.decodeBase64(theSecret);
    return new String(decodedBytes, "UTF-8");
}

From source file:gsn.http.FieldUpload.java

public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    String msg;//from   ww w.jav  a 2s.co m
    Integer code;
    PrintWriter out = res.getWriter();
    ArrayList<String> paramNames = new ArrayList<String>();
    ArrayList<String> paramValues = new ArrayList<String>();

    //Check that we have a file upload request
    boolean isMultipart = ServletFileUpload.isMultipartContent(req);
    if (!isMultipart) {
        out.write("not multipart!");
        code = 666;
        msg = "Error post data is not multipart!";
        logger.error(msg);
    } else {
        // Create a factory for disk-based file items
        FileItemFactory factory = new DiskFileItemFactory();

        // Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload(factory);

        // Set overall request size constraint
        upload.setSizeMax(5 * 1024 * 1024);

        List items;
        try {
            // Parse the request
            items = upload.parseRequest(req);

            //building xml data out of the input
            String cmd = "";
            String vsname = "";
            Base64 b64 = new Base64();
            StringBuilder sb = new StringBuilder("<input>\n");
            Iterator iter = items.iterator();
            while (iter.hasNext()) {
                FileItem item = (FileItem) iter.next();
                if (item.getFieldName().equals("vsname")) {
                    //define which cmd block is sent
                    sb.append("<vsname>" + item.getString() + "</vsname>\n");
                    vsname = item.getString();
                } else if (item.getFieldName().equals("cmd")) {
                    //define which cmd block is sent
                    cmd = item.getString();
                    sb.append("<command>" + item.getString() + "</command>\n");
                    sb.append("<fields>\n");
                } else if (item.getFieldName().split(";")[0].equals(cmd)) {
                    //only for the defined cmd       
                    sb.append("<field>\n");
                    sb.append("<name>" + item.getFieldName().split(";")[1] + "</name>\n");
                    paramNames.add(item.getFieldName().split(";")[1]);
                    if (item.isFormField()) {
                        sb.append("<value>" + item.getString() + "</value>\n");
                        paramValues.add(item.getString());
                    } else {
                        sb.append("<value>" + new String(b64.encode(item.get())) + "</value>\n");
                        paramValues.add(new String(b64.encode(item.get())));
                    }
                    sb.append("</field>\n");
                }
            }
            sb.append("</fields>\n");
            sb.append("</input>\n");

            //do something with xml aka statement.toString()

            AbstractVirtualSensor vs = null;
            try {
                vs = Mappings.getVSensorInstanceByVSName(vsname).borrowVS();
                vs.dataFromWeb(cmd, paramNames.toArray(new String[] {}),
                        paramValues.toArray(new Serializable[] {}));
            } catch (VirtualSensorInitializationFailedException e) {
                logger.warn("Sending data back to the source virtual sensor failed !: " + e.getMessage(), e);
            } finally {
                Mappings.getVSensorInstanceByVSName(vsname).returnVS(vs);
            }

            code = 200;
            msg = "The upload to the virtual sensor went successfully! (" + vsname + ")";
        } catch (ServletFileUpload.SizeLimitExceededException e) {
            code = 600;
            msg = "Upload size exceeds maximum limit!";
            logger.error(msg, e);
        } catch (Exception e) {
            code = 500;
            msg = "Internal Error: " + e;
            logger.error(msg, e);
        }

    }
    //callback to the javascript
    out.write("<script>window.parent.GSN.msgcallback('" + msg + "'," + code + ");</script>");
}