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

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

Introduction

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

Prototype

public static byte[] encodeBase64(final byte[] binaryData) 

Source Link

Document

Encodes binary data using the base64 algorithm but does not chunk the output.

Usage

From source file:com.threerings.getdown.tools.AppletParamSigner.java

public static void main(String[] args) {
    try {/* ww w . j a  va  2  s  . c  o m*/
        if (args.length != 7) {
            System.err
                    .println("AppletParamSigner keystore storepass alias keypass " + "appbase appname imgpath");
            System.exit(255);
        }

        String keystore = args[0];
        String storepass = args[1];
        String alias = args[2];
        String keypass = args[3];
        String appbase = args[4];
        String appname = args[5];
        String imgpath = args[6];
        String params = appbase + appname + imgpath;

        KeyStore store = KeyStore.getInstance("JKS");
        store.load(new BufferedInputStream(new FileInputStream(keystore)), storepass.toCharArray());
        PrivateKey key = (PrivateKey) store.getKey(alias, keypass.toCharArray());
        Signature sig = Signature.getInstance("SHA1withRSA");
        sig.initSign(key);
        sig.update(params.getBytes());
        String signed = new String(Base64.encodeBase64(sig.sign()));
        System.out.println("<param name=\"appbase\" value=\"" + appbase + "\" />");
        System.out.println("<param name=\"appname\" value=\"" + appname + "\" />");
        System.out.println("<param name=\"bgimage\" value=\"" + imgpath + "\" />");
        System.out.println("<param name=\"signature\" value=\"" + signed + "\" />");

    } catch (Exception e) {
        System.err.println("Failed to produce signature.");
        e.printStackTrace();
    }
}

From source file:com.manning.blogapps.chapter10.examples.AuthPost.java

public static void main(String[] args) throws Exception {
    if (args.length < 4) {
        System.out.println("USAGE: authpost <username> <password> <filepath> <url>");
        System.exit(-1);//from  w w w  .  ja  va 2 s  .  c om
    }
    String credentials = args[0] + ":" + args[1];
    String filepath = args[2];
    String url = args[3];

    HttpClient httpClient = new HttpClient();
    EntityEnclosingMethod method = new PostMethod(url);
    method.setRequestHeader("Authorization",
            "Basic " + new String(Base64.encodeBase64(credentials.getBytes())));

    File upload = new File(filepath);
    method.setRequestHeader("Title", upload.getName());
    method.setRequestBody(new FileInputStream(upload));

    String contentType = "application/atom+xml; charset=utf8";
    if (filepath.endsWith(".gif"))
        contentType = "image/gif";
    else if (filepath.endsWith(".jpg"))
        contentType = "image/jpg";
    method.setRequestHeader("Content-type", contentType);

    httpClient.executeMethod(method);
    System.out.println(method.getResponseBodyAsString());
}

From source file:com.manning.blogapps.chapter10.examples.AuthPostJava.java

public static void main(String[] args) throws Exception {
    if (args.length < 4) {
        System.out.println("USAGE: authpost <username> <password> <filepath> <url>");
        System.exit(-1);//  ww w. j a v a 2  s.  c om
    }
    String credentials = args[0] + ":" + args[1];
    String filepath = args[2];

    URL url = new URL(args[3]);
    URLConnection conn = url.openConnection();
    conn.setDoOutput(true);

    conn.setRequestProperty("Authorization",
            "Basic " + new String(Base64.encodeBase64(credentials.getBytes())));

    File upload = new File(filepath);
    conn.setRequestProperty("name", upload.getName());

    String contentType = "application/atom+xml; charset=utf8";
    if (filepath.endsWith(".gif"))
        contentType = "image/gif";
    else if (filepath.endsWith(".jpg"))
        contentType = "image/jpg";
    conn.setRequestProperty("Content-type", contentType);

    BufferedInputStream filein = new BufferedInputStream(new FileInputStream(upload));
    BufferedOutputStream out = new BufferedOutputStream(conn.getOutputStream());
    byte buffer[] = new byte[8192];
    for (int count = 0; count != -1;) {
        count = filein.read(buffer, 0, 8192);
        if (count != -1)
            out.write(buffer, 0, count);
    }
    filein.close();
    out.close();

    String s = null;
    BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    while ((s = in.readLine()) != null) {
        System.out.println(s);
    }
}

From source file:OldExtractor.java

/**
 * @param args the command line arguments
 *///www .  j ava2 s  . co m
public static void main(String[] args) {
    // TODO code application logic here
    String bingUrl = "https://api.datamarket.azure.com/Bing/Search/Web?$top=10&$format=Atom&Query=%27gates%27";
    //Provide your account key here.
    String accountKey = "ghTYY7wD6LpyxUO9VRR7e1f98WFhHWYERMcw87aQTqQ";
    //  String accountKey = "xqbCjT87/MQz25JWdRzgMHdPkGYnOz77IYmP5FUIgC8";

    byte[] accountKeyBytes = Base64.encodeBase64((accountKey + ":" + accountKey).getBytes());
    String accountKeyEnc = new String(accountKeyBytes);

    try {
        URL url = new URL(bingUrl);
        URLConnection urlConnection = url.openConnection();

        urlConnection.setRequestProperty("Authorization", "Basic " + accountKeyEnc);
        InputStream inputStream = (InputStream) urlConnection.getContent();
        byte[] contentRaw = new byte[urlConnection.getContentLength()];
        inputStream.read(contentRaw);
        String content = new String(contentRaw);
        //System.out.println(content);
        try {
            File file = new File("Results.xml");
            FileWriter fileWriter = new FileWriter(file);
            fileWriter.write(content);
            //fileWriter.write("a test");
            fileWriter.flush();
            fileWriter.close();

        } catch (IOException e) {
            System.out.println(e);
        }

        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

        try {
            //System.out.println("here");
            //Using factory get an instance of document builder
            DocumentBuilder db = dbf.newDocumentBuilder();

            //parse using builder to get DOM representation of the XML file
            Document dom = db.parse("Results.xml");
            Element docEle = (Element) dom.getDocumentElement();

            //get a nodelist of elements

            NodeList nl = docEle.getElementsByTagName("d:Url");
            if (nl != null && nl.getLength() > 0) {
                for (int i = 0; i < nl.getLength(); i++) {

                    //get the employee element
                    Element el = (Element) nl.item(i);
                    // System.out.println("here");
                    System.out.println(el.getTextContent());

                    //get the Employee object
                    //Employee e = getEmployee(el);

                    //add it to list
                    //myEmpls.add(e);
                }
            }
            NodeList n2 = docEle.getElementsByTagName("d:Title");
            if (n2 != null && n2.getLength() > 0) {
                for (int i = 0; i < n2.getLength(); i++) {

                    //get the employee element
                    Element e2 = (Element) n2.item(i);
                    // System.out.println("here");
                    System.out.println(e2.getTextContent());

                    //get the Employee object
                    //Employee e = getEmployee(el);

                    //add it to list
                    //myEmpls.add(e);
                }
            }

            NodeList n3 = docEle.getElementsByTagName("d:Description");
            if (n3 != null && n3.getLength() > 0) {
                for (int i = 0; i < n3.getLength(); i++) {

                    //get the employee element
                    Element e3 = (Element) n3.item(i);
                    // System.out.println("here");
                    System.out.println(e3.getTextContent());

                    //get the Employee object
                    //Employee e = getEmployee(el);

                    //add it to list
                    //myEmpls.add(e);
                }
            }

        } catch (SAXException se) {
            se.printStackTrace();
        } catch (ParserConfigurationException pe) {
            pe.printStackTrace();
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }

    } catch (IOException e) {
        System.out.println(e);
    }

    //The content string is the xml/json output from Bing.

}

From source file:com.adobe.aem.demomachine.Base64Encoder.java

public static void main(String[] args) throws IOException {

    String value = null;/*from  w w w  .  j av a 2  s  . c  o  m*/

    // Command line options for this tool
    Options options = new Options();
    options.addOption("v", true, "Value");
    CommandLineParser parser = new BasicParser();
    try {
        CommandLine cmd = parser.parse(options, args);

        if (cmd.hasOption("v")) {
            value = cmd.getOptionValue("v");
        }

        if (value == null) {
            System.out.println("Command line parameters: -v value");
            System.exit(-1);
        }

    } catch (ParseException ex) {

        logger.error(ex.getMessage());

    }

    byte[] encodedBytes = Base64.encodeBase64(value.getBytes());
    System.out.println(new String(encodedBytes));

}

From source file:com.lexmark.saperion.util.ClientMultipartFormPost.java

public static void main(String[] args) throws Exception {
    String userName = "amolugu";
    String password = "ecm";
    String authString = userName + ":" + password;
    byte[] authEncBytes = Base64.encodeBase64(authString.getBytes());
    String authStringEnc = new String(authEncBytes);
    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {/*from   ww w.  j  av  a 2  s.com*/
        HttpPost httpPost = new HttpPost("https://ecm-service.psft.co/ecms/documents");

        //http
        httpPost.addHeader("Authorization", "Basic " + authStringEnc);
        httpPost.addHeader("Accept", "application/json");
        httpPost.addHeader("saTenant", "india");
        httpPost.addHeader("saLicense", "1");
        httpPost.addHeader("Content-Type", "application/octet-stream");

        FileBody bin = new FileBody(new File("C:\\Users\\Aditya.Molugu\\workspace\\RestClient\\Binaries.txt"));
        StringBody comment = new StringBody("A binary file of some kind", ContentType.TEXT_PLAIN);

        HttpEntity reqEntity = MultipartEntityBuilder.create().addPart("bin", bin).addPart("comment", comment)
                .build();

        //HttpBo
        httpPost.setEntity(reqEntity);

        System.out.println("executing request " + httpPost.getRequestLine());
        CloseableHttpResponse response = httpclient.execute(httpPost);
        try {
            System.out.println("----------------------------------------");
            System.out.println(response.getStatusLine());
            HttpEntity resEntity = response.getEntity();
            if (resEntity != null) {
                System.out.println("Response content length: " + resEntity.getContentLength());
            }
            EntityUtils.consume(resEntity);
        } finally {
            response.close();
        }
    } finally {
        httpclient.close();
    }
}

From source file:com.vimukti.accounter.developer.api.PublicKeyGenerator.java

/**
 * @param args//from   w  ww. ja  va2 s . c o  m
 * @throws NoSuchProviderException
 * @throws NoSuchAlgorithmException
 * @throws InvalidKeySpecException
 * @throws IOException
 * @throws CertificateException
 * @throws KeyStoreException
 * @throws UnrecoverableEntryException
 * @throws URISyntaxException
 */
public static void main(String[] args) throws KeyStoreException, NoSuchAlgorithmException, CertificateException,
        IOException, UnrecoverableEntryException {
    FileInputStream is = new FileInputStream(
            ServerConfiguration.getConfig() + File.separator + "license.keystore");
    KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
    String password = "liceseStorePassword";
    keystore.load(is, password.toCharArray());
    PrivateKeyEntry entry = (PrivateKeyEntry) keystore.getEntry("licenseAlias",
            new PasswordProtection(ServerConfiguration.getLicenseKeystorePWD().toCharArray()));
    Key key = entry.getPrivateKey();
    System.out.println((PrivateKey) key);
    PublicKey publicKey = entry.getCertificate().getPublicKey();
    System.out.println(publicKey);

    byte[] encoded = publicKey.getEncoded();
    byte[] encodeBase64 = Base64.encodeBase64(encoded);
    System.out.println("Public Key:" + new String(encodeBase64));

}

From source file:com.mindquarry.management.user.UserManagementClient.java

public static void main(String[] args) {
    log = LogFactory.getLog(UserManagementClient.class);
    log.info("Starting user management client..."); //$NON-NLS-1$

    // parse command line arguments
    CommandLine line = null;/*  www.  j av  a  2s .com*/
    CommandLineParser parser = new GnuParser();
    try {
        // parse the command line arguments
        line = parser.parse(options, args);
    } catch (ParseException e) {
        // oops, something went wrong
        log.error("Parsing of command line failed."); //$NON-NLS-1$
        printUsage();
        return;
    }
    // retrieve login data
    System.out.print("Please enter your login ID: "); //$NON-NLS-1$

    String user = readString();
    user = user.trim();

    System.out.print("Please enter your new password: "); //$NON-NLS-1$

    String password = readString();
    password = password.trim();
    password = new String(DigestUtils.md5(password));
    password = new String(Base64.encodeBase64(password.getBytes()));

    // start PWD change client
    UserManagementClient manager = new UserManagementClient();
    try {
        if (line.hasOption(O_DEL)) {
            manager.deleteUser(line.getOptionValue(O_REPO), ADMIN_LOGIN, ADMIN_PWD, user, password);
        } else {
            manager.changePwd(line.getOptionValue(O_REPO), ADMIN_LOGIN, ADMIN_PWD, user, password);
        }
    } catch (Exception e) {
        log.error("Error while applying password changes.", e); //$NON-NLS-1$
    }
    log.info("User management client finished successfully."); //$NON-NLS-1$
}

From source file:com.hadoopvietnam.commons.crypt.J2MECrypto.java

public static void main(String[] args) {
    J2MECrypto crypto = new J2MECrypto("LetfyActionCrypto".getBytes());
    String code = System.currentTimeMillis() + " " + "tk1cntt@gmail.com" + " " + System.currentTimeMillis();
    String encode = new String(Base64.encodeBase64(crypto.encrypt((code).getBytes())));
    System.out.println(encode);//from   w w w  . j  a va  2 s.c o m
    String decode = new String(crypto.decrypt(Base64.decodeBase64(encode.getBytes())));
    System.out.println(decode);
    System.out.println(DigestUtils.md5Hex(code));
}

From source file:com.tcs.ebw.security.EBWSecurity.java

public static void main(String args[]) {

    try {//from   w  w w  . ja v a 2  s. co m

        EBWSecurity sec = new EBWSecurity();

        String testData2 = "Pramodh B Somashekara 231259 Channels !@#$%^&*()";

        if (args.length > 0)
            testData2 = (String) args[0];

        if (testData2 == null) {

            System.out.println("No Arguements in command line...Continuing with 'ELECTUSR'");

            testData2 = "ELECTUSR";

        }

        byte[] enc;

        System.out.println("----------------ENCRYPTION-------------");

        System.out.println("Original String:" + testData2);

        /** Set IMRS Key here **/

        sec.setSecretKey(sec.getSecretKey());

        testData2 = (new String(Base64.encodeBase64(sec.encryptSymmetric(testData2.getBytes()))));

        System.out.println("After Base64 Encode:" + testData2);

        testData2 = java.net.URLEncoder.encode(testData2, "utf-8");

        System.out.println("Encrypted[Base64+EncryptAlgo+URLEncoded][" + testData2 + "]");

        System.out.println("---------------DECRYPTION--------------");

        System.out.println("Encrypted[Base64+EncryptAlgo+URLEncoded]" + testData2);

        testData2 = java.net.URLDecoder.decode(testData2, "utf-8");

        testData2 = new String(sec.decryptSymmetric(
                Base64.decodeBase64(java.net.URLDecoder.decode(testData2, "utf-8").getBytes())));

        System.out.println("Decrypted[Base64+EncryptAlgo][" + testData2 + "]");

    } catch (NoSuchAlgorithmException e) {

        // TODO Auto-generated catch block

        e.printStackTrace();

    } catch (NoSuchPaddingException e) {

        // TODO Auto-generated catch block

        e.printStackTrace();

    } catch (BadPaddingException e) {

        // TODO Auto-generated catch block

        e.printStackTrace();

    } catch (InvalidKeyException e) {

        // TODO Auto-generated catch block

        e.printStackTrace();

    } catch (IllegalBlockSizeException e) {

        // TODO Auto-generated catch block

        e.printStackTrace();

    } catch (Exception e) {

        // TODO Auto-generated catch block

        e.printStackTrace();

    }

}