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:net.arccotangent.pacchat.filesystem.KeyManager.java

private static void saveKeys(PrivateKey privkey, PublicKey pubkey) {
    km_log.i("Saving keys to disk.");

    X509EncodedKeySpec pubSpec = new X509EncodedKeySpec(pubkey.getEncoded());
    PKCS8EncodedKeySpec privSpec = new PKCS8EncodedKeySpec(privkey.getEncoded());

    try {//from w w w. j av a2  s  . c  o m
        km_log.i(pubkeyFile.createNewFile() ? "Creation of public key file successful."
                : "Creation of public key file failed!");

        FileOutputStream pubOut = new FileOutputStream(pubkeyFile);
        pubOut.write(Base64.encodeBase64(pubSpec.getEncoded()));
        pubOut.flush();
        pubOut.close();

    } catch (IOException e) {
        km_log.e("Error while saving public key!");
        e.printStackTrace();
    }

    try {
        km_log.i(privkeyFile.createNewFile() ? "Creation of private key file successful."
                : "Creation of private key file failed!");

        FileOutputStream privOut = new FileOutputStream(privkeyFile);
        privOut.write(Base64.encodeBase64(privSpec.getEncoded()));
        privOut.flush();
        privOut.close();

    } catch (IOException e) {
        km_log.e("Error while saving private key!");
        e.printStackTrace();
    }

    km_log.i("Finished saving keys to disk. Operation appears successful.");
}

From source file:com.shenit.commons.codec.Base64Utils.java

/**
 * ?base 64?//from ww  w .  j a v a  2s .  co m
 * 
 * @param str
 * @param enc
 * @return
 */
public static String base64EncodeHex(String str, String enc) {
    if (StringUtils.isEmpty(str))
        return null;
    enc = enc == null ? HttpUtils.ENC_UTF8 : enc;
    try {
        byte[] encoded = Base64.encodeBase64(str.getBytes(enc));
        return new String(encoded, enc);
    } catch (UnsupportedEncodingException e) {
        LOG.warn("[base64Encode] not supported encoding", e);
    }
    return null;
}

From source file:com.lling.qiqu.utils.AesUtils.java

/**
 * Returns an AES nbit Base64 key//from   www  .j a va 2 s . c om
 *
 * @param keySize Size of the key
 * @return AES 128bit Base64 key
 */
public static String generateKey(int keySize) {
    String key = "";
    KeyGenerator kgen = null;
    try {
        kgen = KeyGenerator.getInstance("AES");
        kgen.init(keySize);
        SecretKey skey = kgen.generateKey();
        byte[] raw = skey.getEncoded();
        key = new String(Base64.encodeBase64(raw));
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
    }
    return key;
}

From source file:com.eviware.soapui.impl.rest.support.handlers.DefaultMediaTypeHandler.java

public String createXmlRepresentation(HttpResponse response) {
    String contentType = response.getContentType();
    String content = response.getContentAsString();

    if (StringUtils.hasContent(contentType) && contentType.toUpperCase().endsWith("XML"))
        return content;

    if (XmlUtils.seemsToBeXml(content))
        return content;
    else if (content == null)
        content = "";

    String result = "<data contentType=\"" + contentType + "\" contentLength=\"" + response.getContentLength()
            + "\">";

    for (int c = 0; c < content.length(); c++) {
        if (content.charAt(c) < 8) {
            return result + new String(Base64.encodeBase64(content.getBytes())) + "</data>";
        }/*from  w w w .j  av  a2 s .  c  om*/
    }

    return result + "<![CDATA[" + content + "]]></data>";
}

From source file:Authentication.HashPassword.java

public String encrypt(String unencryptedString) {
    String encryptedString = null;
    try {/*from ww  w. j a  v a  2 s.c  o m*/
        cipher.init(Cipher.ENCRYPT_MODE, key);
        byte[] plainText = unencryptedString.getBytes(UNICODE_FORMAT);
        byte[] encryptedText = cipher.doFinal(plainText);
        encryptedString = new String(Base64.encodeBase64(encryptedText));
    } catch (Exception e) {
        e.printStackTrace();
    }
    return encryptedString;
}

From source file:com.dv.sharer.restclients.ImageRestClient.java

public Response uploadFile(Integer id, byte[] data) throws Exception {
    data = Base64.encodeBase64(data);
    String dataStr = new String(data);
    Invocation.Builder builder = getWebTarget().path(MessageFormat.format("upload/{0}", new Object[] { id }))
            .request();/*from  w  w  w.j  a  v a  2 s.co  m*/
    String response = builder.post(Entity.entity(dataStr, MediaType.TEXT_PLAIN), String.class);
    Response resp = Response.fromJson(response, Response.class);
    return resp;

}

From source file:com.church.tools.MemberID.java

/**
 * Gets the translated id.//from   w  w  w.jav  a2  s .  c  o  m
 * 
 * @param member_id the member_id
 * @param name the name
 * 
 * @return the translated id
 */
public static String getTranslatedID(int member_id, String name) {
    if (Global.useSimpleMemberID)
        return String.valueOf(member_id);
    int starter = 1000000000;
    String str = Integer.toHexString(starter - member_id).toUpperCase();
    String str2 = "";
    for (int i = str.length(); i < 8; i++)
        str2 += "0";
    str = str2 + str;
    String b64 = new String(Base64.encodeBase64((name + "     ").getBytes())).substring(0, 3).toUpperCase();
    return "#" + b64 + str;
}

From source file:io.appium.java_client.android.ImagesComparisonTest.java

@Test
public void verifyFeaturesMatching() {
    byte[] screenshot = Base64.encodeBase64(driver.getScreenshotAs(OutputType.BYTES));
    FeaturesMatchingResult result = driver.matchImagesFeatures(screenshot, screenshot,
            new FeaturesMatchingOptions().withDetectorName(FeatureDetector.ORB).withGoodMatchesFactor(40)
                    .withMatchFunc(MatchingFunction.BRUTE_FORCE_HAMMING).withEnabledVisualization());
    assertThat(result.getVisualization().length, is(greaterThan(0)));
    assertThat(result.getCount(), is(greaterThan(0)));
    assertThat(result.getTotalCount(), is(greaterThan(0)));
    assertFalse(result.getPoints1().isEmpty());
    assertNotNull(result.getRect1());//w w w. ja  va 2s . co  m
    assertFalse(result.getPoints2().isEmpty());
    assertNotNull(result.getRect2());
}

From source file:com.rackspacecloud.blueflood.io.serializers.CounterRollupSerializationTest.java

@Test
public void testCounterV1RoundTrip() throws IOException {
    CounterRollup c0 = new CounterRollup().withCount(7442245).withSampleCount(1);
    CounterRollup c1 = new CounterRollup().withCount(34454722343L).withSampleCount(10);

    if (System.getProperty("GENERATE_COUNTER_SERIALIZATION") != null) {
        OutputStream os = new FileOutputStream("src/test/resources/serializations/counter_version_"
                + Constants.VERSION_1_COUNTER_ROLLUP + ".bin", false);
        os.write(Base64.encodeBase64(new NumericSerializer.CounterRollupSerializer().toByteBuffer(c0).array()));
        os.write("\n".getBytes());
        os.write(Base64.encodeBase64(new NumericSerializer.CounterRollupSerializer().toByteBuffer(c1).array()));
        os.write("\n".getBytes());
        os.close();//from   ww w .  ja  v  a2  s.co  m
    }

    Assert.assertTrue(new File("src/test/resources/serializations").exists());

    int count = 0;
    int version = 0;
    final int maxVersion = Constants.VERSION_1_COUNTER_ROLLUP;
    while (version <= maxVersion) {
        BufferedReader reader = new BufferedReader(
                new FileReader("src/test/resources/serializations/counter_version_" + version + ".bin"));

        ByteBuffer bb = ByteBuffer.wrap(Base64.decodeBase64(reader.readLine().getBytes()));
        CounterRollup cc0 = NumericSerializer.serializerFor(CounterRollup.class).fromByteBuffer(bb);
        Assert.assertEquals(c0, cc0);

        bb = ByteBuffer.wrap(Base64.decodeBase64(reader.readLine().getBytes()));
        CounterRollup cc1 = NumericSerializer.serializerFor(CounterRollup.class).fromByteBuffer(bb);
        Assert.assertEquals(c1, cc1);

        Assert.assertFalse(cc0.equals(cc1));
        version++;
        count++;
    }

    Assert.assertTrue(count > 0);
}

From source file:cz.muni.fi.mushroomhunter.restclient.MushroomUpdateSwingWorker.java

@Override
protected Integer doInBackground() throws Exception {
    DefaultTableModel model = (DefaultTableModel) restClient.getTblMushroom().getModel();
    int selectedRow = restClient.getTblMushroom().getSelectedRow();

    RestTemplate restTemplate = new RestTemplate();

    String plainCreds = RestClient.USER_NAME + ":" + RestClient.PASSWORD;
    byte[] plainCredsBytes = plainCreds.getBytes();
    byte[] base64CredsBytes = Base64.encodeBase64(plainCredsBytes);
    String base64Creds = new String(base64CredsBytes);

    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);
    List<MediaType> mediaTypeList = new ArrayList<>();
    mediaTypeList.add(MediaType.ALL);//ww  w.j a v a 2  s .co m
    headers.setAccept(mediaTypeList);

    headers.add("Authorization", "Basic " + base64Creds);

    HttpEntity request = new HttpEntity<>(headers);

    ResponseEntity<MushroomDto> responseEntity = restTemplate.exchange(
            RestClient.SERVER_URL + "pa165/rest/mushroom/" + RestClient.getMushroomIDs().get(selectedRow),
            HttpMethod.GET, request, MushroomDto.class);

    MushroomDto mushroomDto = responseEntity.getBody();

    mushroomDto.setName(restClient.getTfMushroomName().getText());

    SimpleDateFormat formatter = new SimpleDateFormat("dd-MMMM-yyyy", new Locale("en_US"));

    //to create date object only month is used, day and year are fixed values
    String dateInString = "01-" + restClient.getComboBoxMushroomStartOfOccurence().getSelectedItem().toString()
            + "-2000";
    mushroomDto.setStartOfOccurence(formatter.parse(dateInString));

    //to create date object only month is used, day and year are fixed values
    dateInString = "01-" + restClient.getComboBoxMushroomEndOfOccurence().getSelectedItem().toString()
            + "-2000";
    mushroomDto.setEndOfOccurence(formatter.parse(dateInString));

    ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
    String json = ow.writeValueAsString(mushroomDto);
    request = new HttpEntity(json, headers);

    restTemplate.exchange(RestClient.SERVER_URL + "pa165/rest/mushroom", HttpMethod.PUT, request,
            MushroomDto.class);
    return selectedRow;
}