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:edu.clemson.lph.utils.Encodings.java

/**
 * Convert a String--normally XML--into normal base64Binary format string (UTF-8).
 * Used for most cases of base64 encoding of content to include in SOAP or other XML 
 * content./*from   ww  w .j  a va2  s  .c om*/
 * @param sXML
 * @return String in base64
 */
public static String getBase64Utf8(String sXML) {
    String sBase64 = null;
    byte[] bytes;
    try {
        bytes = sXML.getBytes("UTF-8");
        byte[] base64Bytes = Base64.encodeBase64(bytes);
        sBase64 = new String(base64Bytes);
    } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return sBase64;
}

From source file:com.ufukuzun.myth.dialect.builder.AjaxEventBindingBuilderTest.java

@Test
public void shouldBuildAjaxEventBinding() {
    byte[] renderFragmentEncoded = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 };
    when(Base64.encodeBase64("newUserForm".getBytes())).thenReturn(renderFragmentEncoded);

    when(ElementAndAttrUtils.getPrefixedName(MythEventAttrProcessor.ATTR_NAME)).thenReturn("myth:event");
    when(ElementAndAttrUtils.getPrefixedName(MythUrlAttrProcessor.ATTR_NAME)).thenReturn("myth:url");
    when(ElementAndAttrUtils.getPrefixedName(MythUpdateAttrProcessor.ATTR_NAME)).thenReturn("myth:update");
    when(ElementAndAttrUtils.getPrefixedName(MythProcessAttrProcessor.ATTR_NAME)).thenReturn("myth:process");

    when(ElementAndAttrUtils.getProcessedAttributeValue(null, element,
            MythEventAttrProcessor.ATTR_NAME_WITH_PREFIX)).thenReturn("click");
    when(ElementAndAttrUtils.getProcessedAttributeValue(null, element,
            MythUrlAttrProcessor.ATTR_NAME_WITH_PREFIX)).thenReturn("/save");

    when(ElementAndAttrUtils.getProcessedAttributeValue(null, "newUserForm")).thenReturn("newUserForm");
    when(element.getAttributeValue(MythUpdateAttrProcessor.ATTR_NAME_WITH_PREFIX)).thenReturn("newUserForm");
    when(ExpressionUtils.splitIdFragments("newUserForm")).thenReturn(Arrays.asList("newUserForm"));
    when(ExpressionUtils.removeRenderExpressions("newUserForm")).thenReturn("newUserForm");

    when(ElementAndAttrUtils.getProcessedAttributeValue(null, "newUserForm")).thenReturn("newUserForm");
    when(element.getAttributeValue(MythProcessAttrProcessor.ATTR_NAME_WITH_PREFIX)).thenReturn("newUserForm");
    when(ExpressionUtils.splitIdFragments("newUserForm")).thenReturn(Arrays.asList("newUserForm"));

    AjaxEventBinding ajaxEventBinding = AjaxEventBindingBuilder.build(null, element);

    String eventAttributeValue = String.format(
            "Myth.ajax(this, {\"update\":[{\"renderFragment\":\"%s\", \"updates\":[\"newUserForm\"]}], \"process\":[\"newUserForm\"], \"url\":\"/save\"}); return false;",
            new String(renderFragmentEncoded));
    assertThat(ajaxEventBinding.getEventAttributeValue(), equalTo(eventAttributeValue));
    assertThat(ajaxEventBinding.getEventAttributeName(), equalTo("onclick"));
}

From source file:testFileHandler.java

public void encrypt(String message, String secretKey, javax.swing.JTextArea ciphertextField) throws Exception {

    MessageDigest md = MessageDigest.getInstance("SHA-1");
    byte[] digestOfPassword = md.digest(secretKey.getBytes("utf-8"));
    byte[] keyBytes = Arrays.copyOf(digestOfPassword, 24);

    SecretKey key = new SecretKeySpec(keyBytes, "DESede");
    Cipher cipher = Cipher.getInstance("DESede");
    cipher.init(Cipher.ENCRYPT_MODE, key);
    // Encode the string into bytes using utf-8
    byte[] plainTextBytes = message.getBytes("utf-8");
    // Encrypt// w  w  w .ja v  a  2s  .com
    byte[] buf = cipher.doFinal(plainTextBytes);
    // Encode bytes to base64 to get a string
    byte[] base64Bytes = Base64.encodeBase64(buf);
    String base64EncryptedString = new String(base64Bytes);

    ciphertextField.setText(base64EncryptedString);
}

From source file:com.cfs.util.AESCriptografia.java

public String gerarChaveRandomica() {
    String chave = null;//from  w w  w . java2 s .c  o  m
    try {
        /* Cria o gerador de chaves */
        KeyGenerator keygen = KeyGenerator.getInstance("AES");
        /* Inicializa o gerador de chaves */
        SecureRandom random = new SecureRandom();
        keygen.init(random);
        /* Cria uma chave */
        SecretKey key = keygen.generateKey();
        /* Captura a chave na forma de bytes */
        byte[] buffer = key.getEncoded();
        /* Codifica a chave gerada */
        byte[] chaveGerada = Base64.encodeBase64(buffer);
        /* Converte a chave para texto */
        chave = new String(chaveGerada, "UTF-8");
    } catch (Exception e) {
        e.printStackTrace();
    }
    /* Retorna a chave */
    return chave;
}

From source file:ke.alphacba.cms.core.util.NoSessionIdUtils.java

private static void writeCookie(HttpServletResponse response, String loginCookieName, String domain,
        int cookieTime, String jsessionId, boolean httpOnly) {

    String cookieValue = new String(Base64.encodeBase64(new StringBuilder().append(loginCookieName)
            .append(new Date().getTime()).append(jsessionId).toString().getBytes()));
    Cookie cookie1 = new Cookie(loginCookieName, cookieValue);
    cookie1.setHttpOnly(true);/*from   w  w w  .ja v a2s  . c  o  m*/
    cookie1.setMaxAge(cookieTime);
    cookie1.setPath("/");
    cookie1.setDomain(domain);
    response.addCookie(cookie1);
}

From source file:de.unidue.inf.is.ezdl.dlservices.library.manager.referencesystems.bibsonomy.BibsonomyUtils.java

public BibsonomyUtils(String username, String apiKey) {
    authHeader = "Basic " + new String(Base64.encodeBase64((username + ":" + apiKey).getBytes()));
}

From source file:edu.umn.msi.tropix.client.authentication.impl.LocalUserManagerImpl.java

private String hash(final String password) {
    return new String(Base64.encodeBase64(DigestUtils.sha(password)));
}

From source file:com.amazonaws.services.ec2.model.transform.EC2RequestHandler.java

@Override
public void beforeRequest(Request<?> request) {
    AmazonWebServiceRequest originalRequest = request.getOriginalRequest();
    if (originalRequest instanceof ImportKeyPairRequest) {
        ImportKeyPairRequest importKeyPairRequest = (ImportKeyPairRequest) originalRequest;
        String publicKeyMaterial = importKeyPairRequest.getPublicKeyMaterial();
        String encodedKeyMaterial = new String(Base64.encodeBase64(publicKeyMaterial.getBytes()));
        request.addParameter("PublicKeyMaterial", encodedKeyMaterial);
    }/*from   w  ww  .  ja  v a2  s. c o m*/

    // Request -> Query string marshalling for RequestSpotInstancesRequest is a little tricky since
    // the query string params follow a different form than the XML responses, so we manually set the parameters here.
    else if (originalRequest instanceof RequestSpotInstancesRequest) {
        RequestSpotInstancesRequest requestSpotInstancesRequest = (RequestSpotInstancesRequest) originalRequest;
        int count = 1;
        for (GroupIdentifier group : requestSpotInstancesRequest.getLaunchSpecification()
                .getAllSecurityGroups()) {
            if (group.getGroupId() != null) {
                request.addParameter("LaunchSpecification.SecurityGroupId." + count++, group.getGroupId());
            }
        }

        // Remove any of the incorrect parameters.
        List<String> keysToRemove = new ArrayList<String>();
        for (String parameter : request.getParameters().keySet()) {
            if (parameter.startsWith("LaunchSpecification.GroupSet."))
                keysToRemove.add(parameter);
        }
        for (String key : keysToRemove) {
            request.getParameters().remove(key);
        }
    }

    // If a RunInstancesRequest doesn't specify a ClientToken, fill one in, otherwise 
    // retries could result in unwanted instances being launched in the customer's account.
    else if (originalRequest instanceof RunInstancesRequest) {
        RunInstancesRequest runInstancesRequest = (RunInstancesRequest) originalRequest;
        if (runInstancesRequest.getClientToken() == null) {
            request.getParameters().put("ClientToken", UUID.randomUUID().toString());
        }
    }
}

From source file:com.adobe.communities.ugc.migration.export.UGCExportHelper.java

public static void extractSubNode(JSONWriter object, final Resource node) throws JSONException {
    final ValueMap childVm = node.getValueMap();
    final JSONArray timestampFields = new JSONArray();
    for (Map.Entry<String, Object> prop : childVm.entrySet()) {
        final Object value = prop.getValue();
        if (value instanceof String[]) {
            final JSONArray list = new JSONArray();
            for (String v : (String[]) value) {
                list.put(v);//from   www. j  av a 2 s .com
            }
            object.key(prop.getKey());
            object.value(list);
        } else if (value instanceof GregorianCalendar) {
            timestampFields.put(prop.getKey());
            object.key(prop.getKey());
            object.value(((Calendar) value).getTimeInMillis());
        } else if (value instanceof InputStream) {
            object.key(ContentTypeDefinitions.LABEL_ENCODED_DATA_FIELDNAME);
            object.value(prop.getKey());
            object.key(ContentTypeDefinitions.LABEL_ENCODED_DATA);
            object.value(""); //if we error out on the first read attempt, we need a placeholder value still
            try {
                final InputStream data = (InputStream) value;
                byte[] byteData = new byte[DATA_ENCODING_CHUNK_SIZE];
                int read = 0;
                while (read != -1) {
                    read = data.read(byteData);
                    if (read > 0 && read < DATA_ENCODING_CHUNK_SIZE) {
                        // make a right-size container for the byte data actually read
                        byte[] byteArray = new byte[read];
                        System.arraycopy(byteData, 0, byteArray, 0, read);
                        byte[] encodedBytes = Base64.encodeBase64(byteArray);
                        object.value(new String(encodedBytes));
                    } else if (read == DATA_ENCODING_CHUNK_SIZE) {
                        byte[] encodedBytes = Base64.encodeBase64(byteData);
                        object.value(new String(encodedBytes));
                    }
                }
            } catch (IOException e) {
                object.key(ContentTypeDefinitions.LABEL_ERROR);
                object.value("IOException while getting attachment: " + e.getMessage());
            }
        } else {
            object.key(prop.getKey());
            object.value(prop.getValue());
        }
    }
    if (timestampFields.length() > 0) {
        object.key(ContentTypeDefinitions.LABEL_TIMESTAMP_FIELDS);
        object.value(timestampFields);
    }
    if (node.hasChildren()) {
        object.key(ContentTypeDefinitions.LABEL_SUBNODES);
        object.object();
        for (final Resource subNode : node.getChildren()) {
            object.key(subNode.getName());
            JSONWriter subObject = object.object();
            extractSubNode(subObject, subNode);
            object.endObject();
        }
        object.endObject();
    }
}

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

@Test
public void testSerializerDeserializerV1() throws Exception {
    BluefloodGaugeRollup gauge1 = BluefloodGaugeRollup.buildFromRawSamples(
            Rollups.asPoints(SimpleNumber.class, System.currentTimeMillis(), 300, new SimpleNumber(10L)));
    BluefloodGaugeRollup gauge2 = BluefloodGaugeRollup.buildFromRawSamples(Rollups.asPoints(SimpleNumber.class,
            System.currentTimeMillis() - 100, 300, new SimpleNumber(1234567L)));
    BluefloodGaugeRollup gauge3 = BluefloodGaugeRollup.buildFromRawSamples(Rollups.asPoints(SimpleNumber.class,
            System.currentTimeMillis() - 200, 300, new SimpleNumber(10.4D)));
    BluefloodGaugeRollup gaugesRollup = BluefloodGaugeRollup.buildFromGaugeRollups(Rollups
            .asPoints(BluefloodGaugeRollup.class, System.currentTimeMillis(), 300, gauge1, gauge2, gauge3));
    Assert.assertEquals(3, gaugesRollup.getCount());

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    baos.write(Base64.encodeBase64(new NumericSerializer.GaugeRollupSerializer().toByteBuffer(gauge1).array()));
    baos.write("\n".getBytes());
    baos.write(Base64.encodeBase64(new NumericSerializer.GaugeRollupSerializer().toByteBuffer(gauge2).array()));
    baos.write("\n".getBytes());
    baos.write(Base64.encodeBase64(new NumericSerializer.GaugeRollupSerializer().toByteBuffer(gauge3).array()));
    baos.write("\n".getBytes());
    baos.write(Base64/*from w w  w .ja v  a2s  .  c  o  m*/
            .encodeBase64(new NumericSerializer.GaugeRollupSerializer().toByteBuffer(gaugesRollup).array()));
    baos.write("\n".getBytes());
    baos.close();

    BufferedReader reader = new BufferedReader(
            new InputStreamReader(new ByteArrayInputStream(baos.toByteArray())));

    ByteBuffer bb = ByteBuffer.wrap(Base64.decodeBase64(reader.readLine().getBytes()));
    BluefloodGaugeRollup deserializedGauge1 = NumericSerializer.serializerFor(BluefloodGaugeRollup.class)
            .fromByteBuffer(bb);
    Assert.assertEquals(gauge1, deserializedGauge1);

    bb = ByteBuffer.wrap(Base64.decodeBase64(reader.readLine().getBytes()));
    BluefloodGaugeRollup deserializedGauge2 = NumericSerializer.serializerFor(BluefloodGaugeRollup.class)
            .fromByteBuffer(bb);
    Assert.assertEquals(gauge2, deserializedGauge2);

    bb = ByteBuffer.wrap(Base64.decodeBase64(reader.readLine().getBytes()));
    BluefloodGaugeRollup deserializedGauge3 = NumericSerializer.serializerFor(BluefloodGaugeRollup.class)
            .fromByteBuffer(bb);
    Assert.assertEquals(gauge3, deserializedGauge3);

    bb = ByteBuffer.wrap(Base64.decodeBase64(reader.readLine().getBytes()));
    BluefloodGaugeRollup deserializedGauge4 = NumericSerializer.serializerFor(BluefloodGaugeRollup.class)
            .fromByteBuffer(bb);
    Assert.assertEquals(gaugesRollup, deserializedGauge4);

    Assert.assertFalse(deserializedGauge1.equals(deserializedGauge2));
}