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:com.hyeb.front.controller.CommonController.java

/**
 * //from   w  w w .j av a  2  s  .  co m
 */
@RequestMapping(value = "/public_key", method = RequestMethod.GET)
public @ResponseBody Map<String, String> publicKey(HttpServletRequest request) {
    Assert.notNull(request);
    KeyPair keyPair = RSAUtils.generateKeyPair();
    RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
    RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
    HttpSession session = request.getSession();
    session.setAttribute(PRIVATE_KEY_ATTRIBUTE_NAME, privateKey);

    Map<String, String> data = new HashMap<String, String>();
    data.put("modulus", Base64.encodeBase64String(publicKey.getModulus().toByteArray()));
    data.put("exponent", Base64.encodeBase64String(publicKey.getPublicExponent().toByteArray()));
    return data;
}

From source file:br.eti.fernandoribeiro.cloudserverpro.cli.SignatureClientFilter.java

@Override
public ClientResponse handle(final ClientRequest request) {
    ClientResponse result = null;/*ww w. ja  va  2s . c o  m*/

    try {
        LOGGER.info("Adding signature to request");

        final Map<String, List<Object>> headers = request.getHeaders();

        final List<Object> value = new ArrayList<Object>();

        final DateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");

        final String timestamp = formatter.format(date);

        final Hex encoder = new Hex();

        final MessageDigest digester = MessageDigest.getInstance("SHA1");

        value.add(login + ":" + timestamp + ":" + Base64.encodeBase64String(
                encoder.encode(digester.digest((login + contentLength + timestamp + secretKey).getBytes()))));

        headers.put(HeaderNames.SIGNATURE, value);

        result = getNext().handle(request);
    } catch (final NoSuchAlgorithmException e) {
        LOGGER.log(Level.SEVERE, "Can't handle request", e);
    }

    return result;
}

From source file:es.upm.oeg.examples.watson.service.MachineTranslationService.java

public String translate(String text, String sid) throws IOException, URISyntaxException {

    logger.info("Text to translate :" + text);
    logger.info("Translation type :" + sid);

    List<NameValuePair> qparams = new ArrayList<NameValuePair>();
    qparams.add(new BasicNameValuePair("txt", text));
    qparams.add(new BasicNameValuePair("sid", sid));
    qparams.add(new BasicNameValuePair("rt", "text"));

    Executor executor = Executor.newInstance();
    URI serviceURI = new URI(baseURL).normalize();
    String auth = username + ":" + password;
    byte[] responseB = executor.execute(Request.Post(serviceURI)
            .addHeader("Authorization", "Basic " + Base64.encodeBase64String(auth.getBytes()))
            .bodyString(URLEncodedUtils.format(qparams, "utf-8"), ContentType.APPLICATION_FORM_URLENCODED))
            .returnContent().asBytes();/* ww w.  j  a  v a 2 s  .  c o  m*/

    String response = new String(responseB, "UTF-8");

    logger.info("Translation response :" + response);

    return response;

}

From source file:com.monarchapis.client.authentication.HawkV1RequestProcessor.java

private static String getHawkHash(BaseClient<?> client) {
    try {/*from  w  w w .  j a v a2 s  . co  m*/
        StringBuilder sb = new StringBuilder();
        String httpContent = client.getBody();
        String mimeType = "";
        String content = "";

        if (httpContent != null) {
            mimeType = StringUtils.trimToEmpty(StringUtils.substringBefore(client.getContentType(), ";"));
            content = httpContent;
        }

        sb.append("hawk.1.payload\n");
        sb.append(mimeType);
        sb.append("\n");
        sb.append(content);
        sb.append("\n");

        MessageDigest digest = MessageDigest.getInstance("SHA-256");
        byte[] hash = digest.digest(sb.toString().getBytes("UTF-8"));
        return Base64.encodeBase64String(hash);
    } catch (Exception e) {
        throw new RuntimeException("Could not create hawk hash", e);
    }
}

From source file:com.vmware.o11n.plugin.crypto.service.CryptoEncryptionService.java

/**
 * AES Encryption CBC Mode with PKCS5 Padding
 *
 * @param dataB64 Data to encrypt Base64 encoded
 * @param secretB64 Encryption secret Base64 encoded. For AES128 this should be 128 bits (16 bytes) long. For AES256 this should be 256 bits (32 bytes) long.
 * @param ivB64 Initialization Vector Base64 encoded. 16 bytes long
 * @return Encrypted data Base64 Encoded
 * @throws NoSuchAlgorithmException//  ww w.  j av a  2  s .  c  o  m
 * @throws NoSuchPaddingException
 * @throws InvalidKeyException
 * @throws InvalidAlgorithmParameterException
 * @throws IOException
 * @throws BadPaddingException
 * @throws IllegalBlockSizeException
 */
public String aesEncrypt(String dataB64, String secretB64, String ivB64)
        throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException,
        InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException {
    String encryptedB64 = null;

    final byte[] dataBytes = Base64.decodeBase64(dataB64);
    final byte[] secretBytes = Base64.decodeBase64(secretB64);
    final byte[] ivBytes = Base64.decodeBase64(ivB64);
    final Cipher cipher = Cipher.getInstance(AES_CIPHER);

    cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(secretBytes, "AES"),
            new IvParameterSpec(ivBytes, 0, cipher.getBlockSize()));

    encryptedB64 = Base64.encodeBase64String(cipher.doFinal(dataBytes));
    return encryptedB64;
}

From source file:info.bonjean.beluga.util.ResourcesUtil.java

public static String getRemoteResourceBase64(String url) throws CommunicationException {
    return Base64.encodeBase64String(HTTPUtil.request(url));
}

From source file:br.eti.fernandoribeiro.forge.cloudserverpro.SignatureClientFilter.java

@Override
public ClientResponse handle(final ClientRequest request) {
    ClientResponse result = null;//from   w ww  .  j  a v  a 2s.c  o m

    try {
        ShellMessages.info(shell, "Adding signature to request");

        final Map<String, List<Object>> headers = request.getHeaders();

        final List<Object> value = new ArrayList<Object>();

        final DateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");

        final String timestamp = formatter.format(date);

        final Hex encoder = new Hex();

        final MessageDigest digester = MessageDigest.getInstance("SHA1");

        value.add(login + ":" + timestamp + ":" + Base64.encodeBase64String(
                encoder.encode(digester.digest((login + contentLength + timestamp + secretKey).getBytes()))));

        headers.put(HeaderNames.SIGNATURE, value);

        result = getNext().handle(request);
    } catch (final NoSuchAlgorithmException e) {
        ShellMessages.error(shell, "Can't handle request");
    }

    return result;
}

From source file:com.sap.core.odata.core.debug.DebugInfoBodyTest.java

@Test
public void jsonInputStreamContent() throws Exception {
    ODataResponse response = mock(ODataResponse.class);
    ByteArrayInputStream in = new ByteArrayInputStream(STRING_CONTENT.getBytes());
    when(response.getEntity()).thenReturn(in);
    when(response.getContentHeader()).thenReturn(HttpContentType.APPLICATION_OCTET_STREAM);
    assertEquals(STRING_CONTENT_JSON, appendJson(response));

    in = new ByteArrayInputStream(STRING_CONTENT.getBytes());
    when(response.getEntity()).thenReturn(in);
    when(response.getContentHeader()).thenReturn("image/png");
    assertEquals("\"" + Base64.encodeBase64String(STRING_CONTENT.getBytes()) + "\"", appendJson(response));
}

From source file:enc_mods.aes.java

public String getEncryptedString(String str) {
    String encrypted = "";
    if (secretkey == null) {
        System.out.println("no key");
    } else {/*from   w  w w  .j  a v  a2s  . c  om*/
        try {
            cipher = Cipher.getInstance("AES/ECB/PKCS5PADDING");
            cipher.init(Cipher.ENCRYPT_MODE, secretkey);
            encrypted = Base64.encodeBase64String(cipher.doFinal(str.getBytes("UTF-8")));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    return encrypted;
}

From source file:com.teasoft.teavote.util.AppProperties.java

public void setSecret(String secret) {
    try {/*www .  j a  va2s .com*/
        String first = PBKDF2_ALGORITHM.substring(0, PBKDF2_ALGORITHM.length() - 2);
        String second = "";
        for (int i = 0, j = 12; i < 4; i++) {
            second += first.substring(j - (i * 4), first.length() - i * 4);
        }
        Key aesKey = new SecretKeySpec(second.getBytes(), "AES");
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.ENCRYPT_MODE, aesKey);
        byte[] encrypted = cipher.doFinal(secret.getBytes());
        this.secret = Base64.encodeBase64String(encrypted);
    } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | IllegalBlockSizeException
            | BadPaddingException ex) {
        Logger.getLogger(AppProperties.class.getName()).log(Level.SEVERE, null, ex);
    }
}