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

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

Introduction

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

Prototype

public static String encodeBase64String(final byte[] binaryData) 

Source Link

Document

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

Usage

From source file:cn.lynx.emi.license.GenerateKeyPairs.java

public static void main(String[] args) throws NoSuchAlgorithmException {
    KeyPairGenerator keygen = KeyPairGenerator.getInstance("RSA");
    SecureRandom secrand = new SecureRandom();
    secrand.setSeed("cn.lynx.emi".getBytes());
    keygen.initialize(4096, secrand);/*from   w  w  w. j ava2  s. com*/
    KeyPair keys = keygen.genKeyPair();

    PublicKey pubkey = keys.getPublic();
    PrivateKey prikey = keys.getPrivate();

    String myPubKey = Base64.encodeBase64String(pubkey.getEncoded());
    String myPriKey = Base64.encodeBase64String(prikey.getEncoded());
    System.out.println(prikey);
    System.out.println("pubKey=" + myPubKey);
    System.out.println("priKey=" + myPriKey);
}

From source file:de.britter.beyondstringutils.CodecExample.java

public static void main(String[] args) throws Exception {
    InputStream is = CodecExample.class.getResourceAsStream("asf_logo.png");
    byte[] imgBytes = IOUtils.toByteArray(is);
    String base64 = Base64.encodeBase64String(imgBytes);

    System.out.println(base64);/*  ww  w  .j av  a 2s .  co m*/
}

From source file:licenceexecuter.LicenceExecuter.java

/**
 * @param args the command line arguments
 * @throws java.text.ParseException// w w  w .j a  va2s  . c o  m
 */
public static void main(String[] args) throws Throwable {
    LicenceExecuter licenceExecuter = new LicenceExecuter();
    licenceExecuter.initProperties();

    if (args != null && args.length >= 5) {
        System.out.println(Base64.encodeBase64String(args[4].getBytes()));
        System.out.println(licenceExecuter.properties.getProperty("generateKey"));
        if (Base64.encodeBase64String(args[4].getBytes())
                .equals(licenceExecuter.properties.getProperty("generateKey"))) {
            System.out.println(ControllerKey.encrypt(
                    new ObKeyExecuter().toObject(args[0] + "|" + args[1] + "|" + args[2] + "|" + args[3])));
        } else {
            throw new IllegalArgumentException("InvalidPassword");
        }
        return;
    }
    try {
        licenceExecuter.run();
    } catch (Throwable ex) {
        ex.printStackTrace();
        JOptionPane.showMessageDialog(null, "PROBLEMAS NA EXECUO", "ATENO", JOptionPane.ERROR_MESSAGE);
    }
}

From source file:base64.EncodeBase64.java

public static void main(String[] args) throws IOException {
    BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
    System.out.println("Enter string to encode (input is not escaped):");

    String originalString = reader.readLine();
    String encodedBase64String = Base64.encodeBase64String(originalString.getBytes());
    System.out.println("Your encoded Base64 string :");
    System.out.println(encodedBase64String);
}

From source file:com.doctor.base64.CommonsCodecBase64.java

public static void main(String[] args) {
    String plainText = "Base64??"
            + "??ASCII???"
            + "????Base64";

    // ??/*from w  w  w. ja v a 2 s  . c o  m*/
    String base64String = Base64.encodeBase64String(plainText.getBytes(StandardCharsets.UTF_8));
    System.out.println(base64String);

    String plainTxt = new String(Base64.decodeBase64(base64String), StandardCharsets.UTF_8);
    Preconditions.checkArgument(plainTxt.equals(plainText));

    // ??
    base64String = new String(Base64.encodeBase64Chunked(plainText.getBytes(StandardCharsets.UTF_8)),
            StandardCharsets.UTF_8);
    plainTxt = new String(Base64.decodeBase64(base64String), StandardCharsets.UTF_8);
    Preconditions.checkArgument(plainTxt.equals(plainText));

}

From source file:aiai.apps.gen_keys.GenerateKeys.java

public static void main(String[] args) throws NoSuchAlgorithmException {
    GenerateKeys myKeys = new GenerateKeys(2048);
    myKeys.createKeys();/*  w  w  w  .j av  a2 s.  co  m*/

    String privateKey64 = encodeBase64String(myKeys.getPrivateKey().getEncoded());
    String publicKey64 = Base64.encodeBase64String(myKeys.getPublicKey().getEncoded());
    System.out.println("Private key in base64 format:\n" + privateKey64 + "\n\n");
    System.out.println("Public key in base64 format:\n" + publicKey64);

}

From source file:Naive.java

public static void main(String[] args) throws Exception {
    // Basic access authentication setup
    String key = "CHANGEME: YOUR_API_KEY";
    String secret = "CHANGEME: YOUR_API_SECRET";
    String version = "preview1"; // CHANGEME: the API version to use
    String practiceid = "000000"; // CHANGEME: the practice ID to use

    // Find the authentication path
    Map<String, String> auth_prefix = new HashMap<String, String>();
    auth_prefix.put("v1", "oauth");
    auth_prefix.put("preview1", "oauthpreview");
    auth_prefix.put("openpreview1", "oauthopenpreview");

    URL authurl = new URL("https://api.athenahealth.com/" + auth_prefix.get(version) + "/token");

    HttpURLConnection conn = (HttpURLConnection) authurl.openConnection();
    conn.setRequestMethod("POST");

    // Set the Authorization request header
    String auth = Base64.encodeBase64String((key + ':' + secret).getBytes());
    conn.setRequestProperty("Authorization", "Basic " + auth);

    // Since this is a POST, the parameters go in the body
    conn.setDoOutput(true);/*  w  w w  .  jav  a  2 s  .c  o  m*/
    String contents = "grant_type=client_credentials";
    DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
    wr.writeBytes(contents);
    wr.flush();
    wr.close();

    // Read the response
    BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    StringBuilder sb = new StringBuilder();
    String line;
    while ((line = rd.readLine()) != null) {
        sb.append(line);
    }
    rd.close();

    // Decode from JSON and save the token for later
    String response = sb.toString();
    JSONObject authorization = new JSONObject(response);
    String token = authorization.get("access_token").toString();

    // GET /departments
    HashMap<String, String> params = new HashMap<String, String>();
    params.put("limit", "1");

    // Set up the URL, method, and Authorization header
    URL url = new URL("https://api.athenahealth.com/" + version + "/" + practiceid + "/departments" + "?"
            + urlencode(params));
    conn = (HttpURLConnection) url.openConnection();
    conn.setRequestMethod("GET");
    conn.setRequestProperty("Authorization", "Bearer " + token);

    rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    sb = new StringBuilder();
    while ((line = rd.readLine()) != null) {
        sb.append(line);
    }
    rd.close();

    response = sb.toString();
    JSONObject departments = new JSONObject(response);
    System.out.println(departments.toString());

    // POST /appointments/{appointmentid}/notes
    params = new HashMap<String, String>();
    params.put("notetext", "Hello from Java!");

    url = new URL("https://api.athenahealth.com/" + version + "/" + practiceid + "/appointments/1/notes");
    conn = (HttpURLConnection) url.openConnection();
    conn.setRequestMethod("POST");
    conn.setRequestProperty("Authorization", "Bearer " + token);

    // POST parameters go in the body
    conn.setDoOutput(true);
    contents = urlencode(params);
    wr = new DataOutputStream(conn.getOutputStream());
    wr.writeBytes(contents);
    wr.flush();
    wr.close();

    rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    sb = new StringBuilder();
    while ((line = rd.readLine()) != null) {
        sb.append(line);
    }
    rd.close();

    response = sb.toString();
    JSONObject note = new JSONObject(response);
    System.out.println(note.toString());
}

From source file:cn.lynx.emi.license.GenerateLicense.java

public static void main(String[] args) throws ClassNotFoundException, ParseException {
    if (args == null || args.length != 4) {
        System.err.println("Please provide [machine code] [cpu] [memory in gb] [yyyy-MM-dd] as parameter");
        return;//from   w w w  .  j a  va 2s . c  o m
    }

    InputStream is = GenerateLicense.class.getResourceAsStream("/privatekey");
    BufferedReader br = new BufferedReader(new InputStreamReader(is));
    String key = null;
    try {
        key = br.readLine();
    } catch (IOException e) {
        System.err.println(
                "Can't read the private key file, make sure there's a file named \"privatekey\" in the root classpath");
        e.printStackTrace();
        return;
    }

    if (key == null) {
        System.err.println(
                "Can't read the private key file, make sure there's a file named \"privatekey\" in the root classpath");
        return;
    }

    String machineCode = args[0];
    int cpu = Integer.parseInt(args[1]);
    long mem = Long.parseLong(args[2]) * 1024 * 1024 * 1024;
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    long expDate = sdf.parse(args[3]).getTime();

    LicenseBean lb = new LicenseBean();
    lb.setCpuCount(cpu);
    lb.setMemCount(mem);
    lb.setMachineCode(machineCode);
    lb.setExpireDate(expDate);

    try {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ObjectOutputStream os = new ObjectOutputStream(baos);
        os.writeObject(lb);
        os.close();

        String serializedLicense = Base64.encodeBase64String(baos.toByteArray());
        System.out.println("License:" + encrypt(key, serializedLicense));
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:com.sabre.devstudio.samples.dsApiCall.DSApiCalls.java

/**
 * @param args//from w w  w  .j  av a2s  . co  m
 */
public static void main(String[] args) {

    // TODO Auto-generated method stub
    //
    //Request authentication
    //
    final String clientId = "";//Put Your Client Id Here
    final String clientSecret = "";//Put Your Secret Id Here

    //base64 encode clientId and clientSecret
    String encodedClientId = Base64.encodeBase64String((clientId).getBytes());
    String encodedClientSecret = Base64.encodeBase64String((clientSecret).getBytes());

    //Concatenate encoded client and secret strings, separated with colon
    String encodedClientIdSecret = encodedClientId + ":" + encodedClientSecret;

    //Convert the encoded concatenated string to a single base64 encoded string.
    encodedClientIdSecret = Base64.encodeBase64String(encodedClientIdSecret.getBytes());

    DSCommHandler dsC = new DSCommHandler();
    String token = dsC.getAuthToken("https://api.test.sabre.com", encodedClientIdSecret);
    String response = dsC.sendRequest("https://api.test.sabre.com/v1/shop/themes", token);
    //Display the response String
    System.out.println("SDS Response: " + response);

    //Other Example Calls
    //Call Destination Finder, for flights from Las Vegas and 5 day Length
    //String response2 = dsC.sendRequest("https://api.test.sabre.com/v1/shop/flights/fares?origin=LAS&lengthofstay=5", token);
    //Display the String
    //System.out.println("SDS Response: "+response2);

}

From source file:com.wolfsoftco.httpclient.RestClient.java

@SuppressWarnings("resource")
public static void main(String[] args) {
    CloseableHttpClient httpclient = null;
    CloseableHttpResponse response = null;
    try {/*from  w ww  .  j  a  v  a 2 s. c o  m*/
        HttpEntity entity = null;
        String responseHtml = null;
        httpclient = HttpClients.custom().build();

        //Based on CURL line:
        //curl localhost:9090/oauth/token -d "grant_type=password&scope=write&username=greg&password=turnquist" -u foo:bar

        //clientid:secret
        String clientID = "foo:bar";

        HttpUriRequest login = RequestBuilder.post().setUri(new URI(URL))
                .addHeader("Authorization", "Basic " + Base64.encodeBase64String(clientID.getBytes()))
                .addParameter("grant_type", "password").addParameter("scope", "read")
                .addParameter("username", "greg").addParameter("password", "turnquist").build();

        response = httpclient.execute(login);
        entity = response.getEntity();

        responseHtml = EntityUtils.toString(entity);
        EntityUtils.consume(entity);

        JsonObject jsonObject = null;
        String token = null;
        if (responseHtml.startsWith("{")) {
            JsonParser parser = new JsonParser();
            jsonObject = parser.parse(responseHtml).getAsJsonObject();
            token = jsonObject.get("access_token").getAsString();
        }

        if (token != null) {
            HttpGet request = new HttpGet(URL_FLIGHTS);
            request.addHeader("Authorization", "Bearer " + token);

            response = httpclient.execute(request);
            entity = response.getEntity();
            responseHtml = EntityUtils.toString(entity);
            EntityUtils.consume(entity);
            System.out.println(responseHtml);

        }

    } catch (Exception e) {
        throw new RuntimeException(e);
    } finally {
        try {

            if (httpclient != null)
                httpclient.close();
            if (response != null)
                response.close();

        } catch (IOException e) {
        }
    }
}